标签:javap cab 思想 自带 pre style erase push ble
参考:https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/247626/JavaPythonC%2B%2B-Stack-Solution-O(N
方法1:使用c++自带的find函数和erase函数
class Solution { public: bool isValid(string S) { while(!S.empty()) { auto pos = S.find("abc"); if(pos != string::npos) S.erase(pos,3); else return false; } return true; } };
方法2:使用栈的思想
遇到 ‘c‘ 则检查栈内是否存在‘a‘, ‘b‘,并且要严格按照顺序排列
不合法则直接return false
若for循环终止后仍然未执行return,需要检查栈的大小,解决"aabcabc"这一类字符串
class Solution { public: bool isValid(string S) { vector<char> stack; int n; for(char c : S) { n = stack.size(); if(c == ‘c‘) { if(n < 2 || stack[n-1] != ‘b‘ || stack[n-2] != ‘a‘) return false; stack.pop_back(); stack.pop_back(); } else stack.push_back(c); } return stack.size() == 0; } };
1003. Check If Word Is Valid After Substitutions Medium
标签:javap cab 思想 自带 pre style erase push ble
原文地址:https://www.cnblogs.com/tornado549/p/10542104.html