gpt4 book ai didi

java - 字符串和 2 个字母

转载 作者:行者123 更新时间:2023-11-30 07:06:09 25 4
gpt4 key购买 nike

您好,我是一名学生,我的问题更详细是这样的。

Given a string and two letters (c1 and c2), return a count of the number of times "axb" occurs in the string, where x is any character. For example, given the string "antiaircraft" and the letters 'a' and 't', your method should return 2. The three-letter patterns may overlap. For example, "aaaa" has two occurrences of "axa".

到目前为止我所写的是

public int countAxA(String str, char c1, char c2) {

int count = 0;
for (int i=0; i < str.length(); i++)
{
if (str.charAt(i) == c2)
{
count++;
}
}
return count;
}

因此,根据我的作业,某些输入有效,但其他输入无效。我有什么遗漏的吗?

最佳答案

只需迭代一次并跟踪,如果您碰巧找到第一个字符,则进行前瞻:

public int countAxA(String s, char one, char two) {
char[] cs = s.toCharArray();
int count = 0;
for (int i = 0; i < cs.length - 2; i++) { //don't need to go beyond 3rd last char
if (cs[i] == one && cs[i + 2] == two) {
count++;
}
}
return count;
}

关于java - 字符串和 2 个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40099540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com