![](/img/trans.png)
[英]Return the number of times that the string “hello” appears anywhere in the given string
[英]Return the number of times the string "hello/HELLO/hellO ..." appears anywhere in the given string
返回字符串“hello/Hello/...etc”出現在給定字符串中任意位置的次數。
問題的不同之處在於
字符串 hello 可以是任何情況,即大寫或小寫。
樣本輸入 #1
count("abc 你好 def")
示例輸出 #1
1
樣本輸入 #2
count("嗨。你好。你好。好的")
示例輸出 #2
2
示例輸入 #3
計數(“嗨”)
示例輸出 #3
0
我的方法
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
我得到以下輸出。
誰能告訴我我做錯了什么?
我想知道你的代碼是如何編譯的。 c1 甚至沒有聲明。 我可能會使用這樣的邏輯:
str1.toUpperCase().split(str2.toUpperCase).length()-1
當str1
beginWith 或 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;
}
代碼將str2
向右移動一步,並比較str2
是否與str1
的子字符串相同。 請注意,在str1
= "AAA" 和str2
= "AA" 的情況下,結果為 2,因為第一次和第二次出現的AA
都將匹配。
第1步:
str1: *****
str2: **
第2步:
str1: *****
str2: **
第 3 步:
str1: *****
str2: **
第四步:
str1: *****
str2: **
如果您希望在上述情況下, 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;
}
上面的這個版本是這樣工作的:
第1步:
str1: *****
str2: **
第2步:
str1: *****
str2: **
它不會比較前面步驟中已經比較過的任何字符。
我針對您的示例輸入數據測試了代碼,它們都返回了預期的結果。
如果這是學校作業,請說出來。 否則,您將需要在 google 上提出一個問題,例如:“計算字符串 java 中的出現次數”之類的。 這會給你 - tada - stackoverflow:
希望能有所幫助。
這是一個非常直觀的解決方案:
public static void main(String[] args) {
System.out.println(count("hellohellohellohihihihihihihellohihhihello")); // Prints : 5
}
public static int count(String str){
String str1 = "hello";
String str2 = str.toLowerCase();
int index = 0;
int count = 0;
while (true){
if (str2.contains(str1)){
count++;
str2 = str2.substring(str2.indexOf(str1) + str1.length(), str2.length());
} else {
return count;
}
}
}
//在這里,我們將每個大寫字符更改為小寫,以便與 s2 進行比較 public int count(String str){ String s1="";String s2="hello"; int l2=s2.length(); 整數計數=0;
int l1=str.length();
for(int i=0;i<=l1-l2;i++){
for(int j=i;j<l2+i;j++){
char ch=str.charAt(j);
if(ch>=65&&ch<=90){
ch=(char)(ch+32);
s1=s1+ch;
}
else
s1=s1+ch;
}
if(s1.equals(s2)){
count++;
}
//in that line i have removed the data of string s1 to form new string again
s1="";
}return count;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.