题目:3330. 找到初始输入字符串 I
思路:字符串,时间复杂度0(n)。
默认没有输错的情况ans=1,而输错的情况,只会出现在连续相等字符串,假设这段字符串长度为ct,那么可能的情况为ct-1。累计这些和到ans上即可。
C++版本:
class Solution {
public:
int possibleStringCount(string word) {
int ans=1;
int ct=0;
for(int i=1;i<word.size();i++){
if(word[i]==word[i-1]){
ct++;
}else{
ans+=ct;
ct=0;
}
}
return ans+ct;
}
};
JAVA版本:
class Solution {
public int possibleStringCount(String word) {
int ans=1;
int ct=0;
for(int i=1;i<word.length();i++){
if(word.charAt(i)==word.charAt(i-1)){
ct++;
}else{
ans+=ct;
ct=0;
}
}
return ans+ct;
}
}
Go版本:
func possibleStringCount(word string) int {
ans:=1
ct:=0
for i:=1;i<len(word);i++ {
if word[i]==word[i-1] {
ct++
}else{
ans+=ct
ct=0
}
}
return ans+ct
}