题目1: 拼写单词
解题思路:
使用哈希表存储chars
中每个字母的数量
再使用一个哈希表存储word
中每个字母的数量
将这两个哈希表的键值对逐一进行比较
//先来一个比较通俗易懂的代码
class Solution{
public int countCharacters(String[] words, String chars){
Map<Character, Integer> charsMap = new HashMap<>();
int charsLength = chars.length();
for (int i = 0; i < charsLength; i++){
char c = chars.charAt(i);
charsMap.put(c, charsMap.getOrDefault(c, 0) + 1);
}
int ans = 0;
for (String word : words){
Map<Character, Integer> wordMap = new HashMap<>();
int wordLength = word.length();
for (int i = 0; i < wordLength; i++){
char c = word.charAt(i);
wordMap.put(c, wordMap.getOrDefault(c, 0) + 1);
}
boolean isAns = true;
for (int i = 0; i < wordLength; ++i){
char c = word.charAt(i);
if (charsMap.getOrDefault(c, 0) < wordMap.getOrDefault(c, 0)){
isAns = false;
break;
}
}
if (isAns){
ans += word.length();
}
}
return ans;
}
}
//该代码是以上代码的简写
class Solution {
public int countCharacters(String[] words, String chars){
Map<Character, Integer> charsMap = new HashMap<>();
for(int i = 0; i < chars.length(); i++){
charsMap.put(chars.charAt(i), charsMap.getOrDefault(chars.charAt(i), 0) + 1);
}
int ans = 0;
for(String word : words){
Map<Character, Integer> wordMap = new HashMap<>();
for(int i = 0; i < word.length(); i++){
wordMap.put(word.charAt(i), wordMap.getOrDefault(word.charAt(i), 0) + 1);
}
boolean isAns = true;
for(int i = 0; i < word.length(); i++){
if(charsMap.getOrDefault(word.charAt(i), 0) < wordMap.getOrDefault(word.charAt(i), 0)){
isAns = false;
break;
}
}
if(isAns){
ans += word.length();
}
}
return ans;
}
}
以上代码和【每日编程07】有异曲同工之妙, 并且同时运用到了
getOrDefault()
方法
题目2: 一年中的第几天
解题思路:
1.使用substring根据字符串的特点拆分出年月日
2.判断是否是闰年
闰年: 能整除400或者能整除4却不能整除100
class Solution {
public int dayOfYear(String date) {
int year = Integer.parseInt(date.substring(0, 4));
int month = Integer.parseInt(date.substring(5, 7));
int day = Integer.parseInt(date.substring(8));
int[] monthArray = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)){
monthArray[1] = 29;
}
int sum = 0;
for(int i = 0; i < month - 1; i++){
sum += monthArray[i];
}
sum += day;
return sum;
}
}
Integer.parseInt()
作用:
- 将()内的
String
类型字符串转化为int
类型- ()内的字符串必须是数字
substring
用法:
date = "2022-01-24"
date.substring(0, 4)
: 从下标为0
的位置开始截取到下标为4
的位置(不包括下标为4
的值), 即结果为"2022
";
date.substring(5, 7)
:从下标为5
的位置开始截取到下标为7
的位置(不包括下标为7
的值), 即结果为"01
";
date.substring(8)
:从下标为8
的位置开始截取到最后的值, 即结果为"24
"
题目2.1: 计算日期到天数转换(和题目2有异曲同工之妙)
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
int[] monthArray = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)){
monthArray[1] = 29;
}
int sum = 0;
for(int i = 0; i < month - 1; i++){
sum += monthArray[i];
}
sum += day;
System.out.println(sum);
}
}
}