我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
import java.util.Scanner;
class apples {
public static void main(String args[]) {
Scanner bucky = new Scanner(System.in);
String hello = bucky.nextLine();
int charCount = hello.length() - hello.replaceAll("e", "").length();
System.out.println(charCount);
}
}// COUNTS NUMBER OF "e" CHAR´s within any string input
其他回答
使用Java 8和HashMap,没有任何库来计数所有不同的字符:
private static void countChars(String string) {
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));
hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + ":" + i));
}
这是一个稍微不同风格的递归解决方案:
public static int countOccurrences(String haystack, char needle)
{
return countOccurrences(haystack, needle, 0);
}
private static int countOccurrences(String haystack, char needle, int accumulator)
{
if (haystack.length() == 0) return accumulator;
return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);
}
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;
}
好吧,在一个非常相似的任务中,我偶然发现了这个线程。 我没有看到任何编程语言的限制,因为groovy运行在java虚拟机上: 这里是我如何能够解决我的问题使用Groovy。
"a.b.c.".count(".")
完成了。
那么下面的递归算法呢?这也是线性时间。
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>