Jas*_*ora -3 java loops if-statement
返回字符串"hello/Hello/... etc"出现在给定字符串中的任何位置的次数.
问题的不同之处在于
字符串hello可以是任何情况,即大写或小写.
样本输入#1
计数("abc hello def")
样本输出#1
1
样本输入#2
计数("你好.你好.好.")
样本输出#2
2
样本输入#3
计数("hi")
样本输出#3
0
MyApproach
public int count(String str)
{
String str1="Hello";
int l=str.length();
int l1=str1.length();
if(l<l1)
{
return 0;
}
else
{
int count=0;
int p=0;
int j=0;
while(j<l)
{
char c=str.charAt(j);
char c1=str1.charAt(p);
if(c==c1)
{
p++;
if(p==l1)
{
count++;
p=0;
}
}
else
{
p=0;
}
j++;
}
return count;
}
}
Output TestcaseParameters Testcase Actual Answer Expected
No output 'HELLO how are you' 0 1
Run Code Online (Sandbox Code Playgroud)
我得到以下输出.
谁能告诉我我做错了什么?
我想知道你的代码是如何编译的.c1甚至没有声明.我可能会使用这样的逻辑:
str1.toUpperCase().split(str2.toUpperCase).length()-1
Run Code Online (Sandbox Code Playgroud)
在str1startsWith或endsWith 时,上面的代码不会返回正确的答案str2.这是一个更好的版本:
public static int count(String str1, String str2) {
int count = 0;
int len1 = str1.length();
int len2 = str2.length();
for (int i=0;i<=len1-len2;++i){
if ((str1.substring(i,i+len2)).equalsIgnoreCase(str2)) {
++count;
}
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
代码str2一步一步向右移动,并比较if str2是否与子字符串相同str1.请注意,在情境str1="AAA"和str2="AA"中,结果为2,因为第一次和第二次出现都AA将匹配.
步骤1:
str1: *****
str2: **
Run Code Online (Sandbox Code Playgroud)
第2步:
str1: *****
str2: **
Run Code Online (Sandbox Code Playgroud)
第3步:
str1: *****
str2: **
Run Code Online (Sandbox Code Playgroud)
第4步:
str1: *****
str2: **
Run Code Online (Sandbox Code Playgroud)
如果您希望在上述情况下,AA只计算一次,这里是您的代码:
public static int count(String str1, String str2) {
int count = 0;
int len1 = str1.length();
int len2 = str2.length();
for (int i=0;i<=len1-len2;){
if ((str1.substring(i,i+len2)).equalsIgnoreCase(str2)) {
++count;
i+=len2;
}else{
++i;
}
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
以上版本的工作原理如下:
步骤1:
str1: *****
str2: **
Run Code Online (Sandbox Code Playgroud)
第2步:
str1: *****
str2: **
Run Code Online (Sandbox Code Playgroud)
它不会比较前面步骤中已比较的任何字符.
我根据您的示例输入数据测试了代码,它们都返回了预期的结果.
| 归档时间: |
|
| 查看次数: |
965 次 |
| 最近记录: |