1. 使用Map的时候,统计字数时常用到map.getOrDefault( )方法,当key对应的value不为空时,方法返回值就为value值。如果对应的value值为空,返回值就为0。
for (int i = 0; i < magzine.length(); i++) {
char c=magzine.charAt(i);
mmap.put(c, mmap.getOrDefault(c, 0)+1);
}
2. 遇到统计字符个数相关题常用到map(key-value)来解决,但是可以用数组来代替,索引代表不同字符,数组中放入的值来代表个数。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Map键值对 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String magzine=scanner.next();
String letter=scanner.next();
Map<Character, Integer>mmap=new HashMap<>();
Map<Character, Integer>lmap=new HashMap<>();
for (int i = 0; i < magzine.length(); i++) {
char c=magzine.charAt(i);
mmap.put(c, mmap.getOrDefault(c, 0)+1);
}
for (int i = 0; i < letter.length(); i++) {
char c=letter.charAt(i);
lmap.put(c, lmap.getOrDefault(c, 0)+1);
}
for (char i = 'a'; i < 'z'; i++) {
if(mmap.getOrDefault(i,0)<lmap.getOrDefault(i, 0)) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
}
可以用数组来做:
import java.util.Scanner;
public class 数组 {
static int[]m=new int[26],l=new int[26];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String magzine = scanner.next();
String letter = scanner.next();
for (int i = 0; i < magzine.length(); i++) {
char c = magzine.charAt(i);
m[c-'a']++;
}
for (int i = 0; i < letter.length(); i++) {
char c = letter.charAt(i);
l[c-'a']++;
}
for (int i = 0; i < 26; i++) {
if (m[i]<l[i]) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
}
3. 一个有用的日期模拟器:
public class 日期模拟器 {
static int[] w = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static int year = 1900, month = 1, day = 1;
public static void main(String[] args) {
int ans = 0;
while(year!=1910||month!=12||day!=31) {
if(year%400==0||(year%4==0&&year%100!=0)) w[2]=29;
else w[2]=28;
if(Check()) ans++;
day++;
if(day>w[month]) {
month++;
day=1;
}
if (month>12) {
year++;
month=1;
}
}
System.out.println(ans+1);
}
static boolean Check() {
int a=year;
while (a>0) {
if(a%10==2) return true;
a/=10;
}
int b=month;
while(b>0) {
if(b%10==2) return true;
b/=10;
}
int c=day;
while(c>0) {
if(c%10==2) return true;
c/=10;
}
return false;
}
}