20. valid parentheses 实现 参考资料

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

  • Example 1:
1
2
Input: "()"
Output: true
  • Example 2:
1
2
Input: "()[]{}"
Output: true
  • Example 3:
1
2
Input: "(]"
Output: false
  • Example 4:
1
2
Input: "([)]"
Output: false
  • Example 5:
1
2
Input: "{[]}"
Output: true

判断是否串是否以给定的字符成对出现.

实现

  • java

利用栈,遍历字符串,判断存在左括号则入栈右括号,否则则出栈.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean (String s) {
Stack<Character> stack = new Stack<>();
char[] chars = s.toCharArray();
for (char c : chars){
if ( c == '(') {
stack.push(')');
} else if ( c == '[') {
stack.push(']');
} else if ( c == '{') {
stack.push('}');
}else if (stack.isEmpty() || stack.pop()!= c){
return false;
}
}
return stack.isEmpty();
}
  • scala

正则表达式替换给定字符

1
2
3
4
5
6
7
8
9
10

def (s: String): Boolean = {
var res = s
while (res.contains("()") || res.contains("{}") || res.contains("[]") ) {
res = res.replaceAll("\(\)","")
res = res.replaceAll("\{\}","")
res = res.replaceAll("\[\]","")
}
res.equals("")
}

参考资料