classSolution: defisValid(self, s: str) -> bool: stk = [] for c in s: stk.append(c) if''.join(stk[-3:]) == "abc": stk[-3:] = [] returnlen(stk) == 0
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12
publicclassSolution { publicboolIsValid(string s) { StringBuilder stk = new StringBuilder(); foreach (char c in s) { stk.Append(c); if (stk.Length >= 3 && stk.ToString().Substring(stk.Length - 3).Equals("abc")) { stk.Remove(stk.Length - 3, 3); } } return stk.Length == 0; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10
funcisValid(s string)bool { stk := []byte{} for i, _ := range s { stk = append(stk, s[i]) iflen(stk) >= 3 && string(stk[len(stk) - 3:]) == "abc" { stk = stk[:len(stk) - 3] } } returnlen(stk) == 0 }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13
boolisValid(char * s) { int len = strlen(s); int top = 0; charstack[len]; for (int i = 0; i < len; i++) { char c = s[i]; stack[top++] = c; if (top >= 3 && strncmp(stack + top - 3, "abc", 3) == 0) { top -= 3; } } return top == 0; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11
var isValid = function(s) { const stk = []; for (let i = 0; i < s.length; i++) { const c = s[i]; stk.push(c); if (stk.length >= 3 && stk.slice(stk.length - 3).join("") === "abc") { stk.splice(stk.length - 3, 3); } } return stk.length === 0; };