代码勇士真题:
给定一个字符串由a-z字母组成的字符串s,长度任意字母可任意组合。
要求编写函数找出s中不在a-m范围内的字母个数n,要求函数返回字符串格式为:n/s的长度
例如:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"
public class Printer {
public static String printerError(String s) {
if(s.length()==0){
return "";
}else{
StringBuffer pattern = new StringBuffer("abcdefghijklm");
char[] chr = s.toCharArray();
int errorCount=0;
for(char c:chr){
if(pattern.indexOf(String.valueOf(c))<0){
errorCount++;
}
}
//return "\""+errorCount+"/"+s.length()+"\"";
return String.format("%d/%d",errorCount,s.length());
}
}
public static String printerErrorBest(String s) {
return s.replaceAll("[a-m]", "").length() + "/" + s.length();
}
public static void main(String[] args) {
System.out.println(printerError("aaabbbbhaijjjm"));
}
}
说明:
public String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given
regular expression with the given replacement.
使用replacement参数替换源字符串中所有满足正则表达式的子字符串。
本文解析了一道代码勇士挑战题目,任务是编写一个函数来计算给定字符串中超出'a'到'm'范围的字符数量,并返回该数量与字符串总长度的比例。提供了两种实现方式:一种是遍历字符串并检查每个字符;另一种是利用正则表达式替换方法简化过程。
1040

被折叠的 条评论
为什么被折叠?



