Description
牛客网 2018校招真题 完成括号匹配
Solving Ideas
参考 缺失的括号
Time complexity :
O
(
n
)
O(n)
O(n)
Space complexity :
O
(
1
)
O(1)
O(1)
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author wylu
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] str = br.readLine().toCharArray();
int count = 0;
StringBuilder sb = new StringBuilder();
for (char ch : str) {
if (ch == '[') count++;
else {
if (count == 0) sb.insert(0, '[');
else count--;
}
sb.append(ch);
}
for (int i = 0; i < count; i++) sb.append(']');
System.out.println(sb);
}
}