Check if All A’s Appears Before All B’s
给一个string s, 只有a和b, 看看是不是所有的a都出现在b前边.
这题我看答案咋做的都有. 但是不是设置flag就是sort. flag容易有corn cases, sort明显不是o(n). 我用的是计数法. 先算下有多少a, 然后看看是不是都在b前边.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public boolean checkString(String s) { int countA = 0; for(char c : s.toCharArray()) if(c == 'a') countA++; for(char c : s.toCharArray()){ if(c == 'a') countA--; else break; } if(countA == 0) return true; else return false; } } |