问题是:如果字符串“cat”和“dog”在给定字符串中出现的次数相同,则返回true。示例:catDog(“catdog”)→true; catDog(“catcat”)→false; catDog(“1cat1cadodog”)→true
public boolean catDog(String str) {
int countCat=0;
int countDog=0;
for (int i=0; i<str.length();i++)
{
if (str.charAt(i)== 'c'&& str.length()>=3)
{
if (str.substring(i,i+3).equals("cat"))
countCat++;
}
}
for (int i=0; i<str.length();i++)
{
if (str.charAt(i)== 'd' && str.length()>=3)
{
if (str.substring(i,i+3).equals("dog"))
countDog++;
}
}
if (countCat == countDog)
return true;
else
return false;
}
答案 0 :(得分:2)
str.substring(i,i+3).equals("cat")
i
可能是最后一个而i+3
会出错
答案 1 :(得分:2)
在for
循环条件下,您正在检查整个字符串的长度是否大于等于3
,而不是只检查i
中的部分到结尾。尝试用
str.length() - i >= 3
而不是
str.length() >= 3
答案 2 :(得分:1)
为什么不简单地使用StringUtils#countMatches
?
StringUtils.countMatches(myStr, "cat") == StringUtils.countMatches(myStr, "dog");
不要迷失索引。但是,如果您不想使用此方法,则可以执行调试代码。
答案 3 :(得分:1)
好的,这就是我可能会做的事情:
问题在于您的支票str.length() >= 3
。应该是i + str.length()
。
我还建议您对代码进行一些更改以消除重复。在这里,我提取了计算子字符串出现次数的部分,并将其移动到自己的方法中。检查猫的数量是否等于狗的数量的部分现在调用所述方法两次。
public static void main(String[] args) {
System.out.println(catDog("catdog"));
System.out.println(catDog("catcat"));
System.out.println(catDog("1cat1cadodog"));
System.out.println(catDog("catdogcatc"));//Would previously throw error.
}
public static boolean catDog(String str) {
int countCat = countAppearances(str, "cat");
int countDog = countAppearances(str, "dog");
return countCat == countDog;
}
private static int countAppearances(String str, String key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key.charAt(0) && i + key.length() <= str.length()) {
if (str.substring(i, i + key.length()).equals(key)) {
count++;
}
}
}
return count;
}
答案 4 :(得分:0)
你需要更新你的第一个条件,然后再吐出你的字符串:
if (str.charAt(i)== 'c' && (str.length() - i) >= 3)
{
if (str.substring(i,i+3).equals("cat"))
countCat++;
}
答案 5 :(得分:-1)
public boolean catDog(String str) {
int catCount = 0, dogCount = 0;
//run a for loop to check cat count
//run loop till 2nd last character
for (int i = 0; i < str.length() - 2; i++) {
//now check if the charaters at positions matches "cat"
//if matches then increment cat count
if (str.charAt(i) == 'c' && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 't') {
catCount++;
} else if (str.charAt(i) == 'd' && str.charAt(i + 1) == 'o' && str.charAt(i + 2) == 'g') {
//else check if the charaters at positions matches "dog"
//if matches then increment dog count
dogCount++;
}
}
//check cat count and dog count
if (catCount == dogCount) {
return true;
} else {
return false;
}
}