我是轉換成類似 finite state 的概念。假設當下預計要看到 a,但是字串當下指到的不是 a,就代表要多加一個字元;如果指到的是 a,則代表可以指到字串下一個位置繼續比對。
然後整個字串看完,還是要把檢查當下的 state。只有 stateA 是走完了,stateB 跟 stateC 要額外加上字元。
程式碼
class Solution {
public:
int addMinimum(string word) {
bool stateA = true, stateB = false, stateC = false;
int count = 0, i=0;
while(i < word.size())
{
if(stateA)
{
if(word[i] != 'a') count++;
else i++;
stateA = false;
stateB = true;
}
else if(stateB)
{
if(word[i] != 'b') count++;
else i++;
stateB = false;
stateC = true;
}
else if(stateC)
{
if(word[i] != 'c') count++;
else i++;
stateC = false;
stateA = true;
}
}
if(stateB) count += 2;
else if(stateC) count += 1;
return count;
}
};
沒有留言:
張貼留言