计算字符串中重复的元素
count repeated elements in a string
题目是求一个字符'*'在一个字符串中连续出现的次数。
我已经为它写了一个程序,但是有没有其他有效的方法来解决这个问题
for(int i=0;i<n;i++){
if(s.charAt(i) == '*'){
count=1;
for(int j=i+1;j<n;j++){
if(s.charAt(j) != s.charAt(i))
break;
else
count++;
}
}
}
例如:
input: *a**b output should be 2
input: ***a**b output should be 3
简单一点,线性复杂度(此任务的最高效率):
int stars = 0;
int longest = 0;
for(int i=0;i<n;i++){
if(s.charAt(i) == '*') {
stars++;
longest = Math.max(longest, stars);
//here you can do something useful -
// for example, get max number of consecutive stars
}
else {
//here you can do something useful - in case of if (stars > 0)
// for example - increment number of series
//and don't forget to do the same action after loop finish
stars = 0;
}
}
题目是求一个字符'*'在一个字符串中连续出现的次数。 我已经为它写了一个程序,但是有没有其他有效的方法来解决这个问题
for(int i=0;i<n;i++){
if(s.charAt(i) == '*'){
count=1;
for(int j=i+1;j<n;j++){
if(s.charAt(j) != s.charAt(i))
break;
else
count++;
}
}
}
例如:
input: *a**b output should be 2
input: ***a**b output should be 3
简单一点,线性复杂度(此任务的最高效率):
int stars = 0;
int longest = 0;
for(int i=0;i<n;i++){
if(s.charAt(i) == '*') {
stars++;
longest = Math.max(longest, stars);
//here you can do something useful -
// for example, get max number of consecutive stars
}
else {
//here you can do something useful - in case of if (stars > 0)
// for example - increment number of series
//and don't forget to do the same action after loop finish
stars = 0;
}
}