最大括号深度
标题:最大括号深度 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
现有一字符串仅由 '(',')','{','}','[',']'六种括号组成。
#include <iostream>
#include <stack>
#include <map>
using namespace std;
stack<char> s;
int main() {
string str;
cin >> str;
map<char, char> m;
m.insert({'{', '}'});
m.insert({'[', ']'});
m.insert({'(', ')'});
int out = 0;
int ans = 0;
bool flag = false;
for (int i = 0; i < str.size(); i++) {
if (str[i] == '{' || str[i] == '[' || str[i] == '(') {
flag = true;
s.push(str[i]);
out++;
} else if (m.count(s.top()) && str[i] == m[s.top()]) {
s.pop();
ans = max(ans, out);
out--;
}
}
if (out != 0 || !flag) {
cout << 0 << endl;
} else {
cout << ans << endl;
}
}
import java.util.Scanner;
import java.util.Stack;
import static java.lang.Integer.max;
public class Main {
private static int getDeep(String s) {
int res = 0;
Stack<Character> stk = new Stack<>();
int pos = 0;
while (pos < s.length()) {
if (stk.isEmpty() || !isMatch(stk.peek(), s.charAt(pos))) {
stk.push(s.charAt(pos));
res = max(res, stk.size());
pos++;
continue;
}
while (!stk.isEmpty() && isMatch(stk.peek(), s.charAt(pos))) {
stk.pop();
pos++;
}
}
if (!stk.isEmpty()) {
return 0;
}
return res;
}
private static boolean isMatch(char a, char b) {
boolean res = false;
switch (a) {
case '(':
res = (b == ')');
break;
case '[':
res = (b == ']');
break;
case '{':
res = (b == '}');
break;
default:
break;
}
return res;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (s == null || s.isEmpty() || s.length() == 0) {
System.out.println(0);
return;
}
System.out.println(getDeep(s));
}
}
}
阿里云工作强度 675人发布