我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
我的“惯用的一句话”解决方案:
int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();
不知道为什么使用StringUtils的解决方案是可以接受的。
其他回答
虽然方法可以隐藏它,但没有循环(或递归)就无法计数。但出于性能考虑,您希望使用char[]。
public static int count( final String s, final char c ) {
final char[] chars = s.toCharArray();
int count = 0;
for(int i=0; i<chars.length; i++) {
if (chars[i] == c) {
count++;
}
}
return count;
}
使用replaceAll(即RE)听起来不是最好的方法。
那么下面的递归算法呢?这也是线性时间。
import java.lang.*;
import java.util.*;
class longestSubstr{
public static void main(String[] args){
String s="ABDEFGABEF";
int ans=calc(s);
System.out.println("Max nonrepeating seq= "+ans);
}
public static int calc(String s)
{//s.s
int n=s.length();
int max=1;
if(n==1)
return 1;
if(n==2)
{
if(s.charAt(0)==s.charAt(1)) return 1;
else return 2;
}
String s1=s;
String a=s.charAt(n-1)+"";
s1=s1.replace(a,"");
// System.out.println(s+" "+(n-2)+" "+s.substring(0,n-1));
max=Math.max(calc(s.substring(0,n-1)),(calc(s1)+1));
return max;
}
}
</i>
这个怎么样。它没有在底层使用regexp,因此应该比其他一些解决方案更快,并且不会使用循环。
int count = line.length() - line.replace(".", "").length();
下面是一个没有循环的解决方案:
public static int countOccurrences(String haystack, char needle, int i){
return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}
System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));
嗯,有一个循环,但它是看不见的:-)
——约拿单
public static int countOccurrences(String container, String content){
int lastIndex, currIndex = 0, occurrences = 0;
while(true) {
lastIndex = container.indexOf(content, currIndex);
if(lastIndex == -1) {
break;
}
currIndex = lastIndex + content.length();
occurrences++;
}
return occurrences;
}