[AlgoExpert] Longest Balanced Substring

Longest Balanced Substring

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int longestBalancedSubstring(string str) {
vector<int> st{-1};
int n = str.length(), res = 0;
for(int i = 0; i < n; i++) {
if(str[i] == '(') st.push_back(i);
else {
if(st.back() == -1 or str[st.back()] == ')') st.push_back(i);
else {
st.pop_back();
res = max(res, i - st.back());
}
}
}
return res;
}


Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/longest-balanced-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.