题解 | #计算某字符出现次数#
计算某字符出现次数
https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1
自己解法
思路:用Scaner读取,分别用两个字符串存取读取的两行,然后遍历
优点;好理解
缺点:运行速度慢,占用空间大
时间复杂度:O(n)
可优化点:1.可以把字符串转为字符数组;2.遍历时可以过滤掉非字符的字符,减少循环体执行
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String strs = in.nextLine();
String c = in.next();
strs = strs.toLowerCase();
c = c.toLowerCase();
char cl = c.charAt(0);
int count = 0;
for(int i = 0; i < strs.length();i++){
if(strs.charAt(i) == cl){
count ++;
}
}
System.out.println(count);
}
}
题解解法
思路:用Scaner读取,分别用两个字符串存取读取的两行,然后替换字符串中的目标字符为空,计算替换前后的字符串长度差即为字符出现的次数
优点;代码简洁
缺点:运行速度慢,占用空间大
时间复杂度:O(1)
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String strs1 = in.nextLine();
String strs2 = in.nextLine();
strs1 = strs1.toLowerCase();
strs2 = strs2.toLowerCase();
String strs3 = strs1.replaceAll(strs2,"");
System.out.println(strs1.length() - strs3.length());
}
}
榜一解法
思路:用BufferReader代替读取,加快IO速度,把读取的两行转为字符数组和小写,然后遍历,遍历时去掉非字母和数字
优点;运行速度快,占用空间少
时间复杂度:O(n)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] chars1 = br.readLine().toLowerCase().toCharArray();
char[] chars2 = br.readLine().toLowerCase().toCharArray();
int count = 0;
for (int i = 0; i < chars1.length; i++) {
if ((chars1[i] >= 65 || chars1[i] < 90) && (chars1[i] == chars2[0])) {
count++;
}
}
System.out.println(count);
}
}
#计算某字符出现次数#