classSolution: deffindTheLongestBalancedSubstring(self, s: str) -> int: ans = pre = cur = 0 for i, c inenumerate(s): cur += 1 if i == len(s) - 1or c != s[i + 1]: if c == '1': ans = max(ans, min(pre, cur) * 2) pre = cur cur = 0 return ans
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicintfindTheLongestBalancedSubstring(String S) { vars= S.toCharArray(); intans=0, pre = 0, cur = 0, n = s.length; for (inti=0; i < n; ++i) { ++cur; if (i == s.length - 1 || s[i] != s[i + 1]) { if (s[i] == '1') ans = Math.max(ans, Math.min(pre, cur) * 2); pre = cur; cur = 0; } } return ans; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intfindTheLongestBalancedSubstring(string s){ int ans = 0, pre = 0, cur = 0, n = s.length(); for (int i = 0; i < n; ++i) { ++cur; if (i == s.length() - 1 || s[i] != s[i + 1]) { if (s[i] == '1') ans = max(ans, min(pre, cur) * 2); pre = cur; cur = 0; } } return ans; } };
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcfindTheLongestBalancedSubstring(s string) (ans int) { pre, cur := 0, 0 for i, c := range s { cur++ if i == len(s)-1 || byte(c) != s[i+1] { if c == '1' { ans = max(ans, min(pre, cur)*2) } pre = cur cur = 0 } } return }
funcmin(a, b int)int { if a > b { return b }; return a } funcmax(a, b int)int { if a < b { return b }; return a }