-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidParentheses.java
140 lines (119 loc) · 3.72 KB
/
ValidParentheses.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package me.rainking;
import java.util.LinkedList;
/**
* @author Rain
* @date 2018/5/24
*/
public class ValidParentheses {
public static void main(String[] args) {
ValidParentheses o = new ValidParentheses();
String strArr[] = {"()", "()[]{}", "(]", "([)]", "{[]}", "", "]"};
for (String str : strArr) {
System.out.println(o.isValid3(str));
}
}
/**
* 不使用栈
*/
public boolean isValid(String s) {
if (s.length() % 2 == 1)
return false;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
sb.append(s.charAt(i));
} else if (s.charAt(i) == ')') {
if (sb.length() != 0 && sb.charAt(sb.length() - 1) == '(') {
sb.deleteCharAt(sb.length() - 1);
} else {
return false;
}
} else if (s.charAt(i) == ']') {
if (sb.length() != 0 && sb.charAt(sb.length() - 1) == '[') {
sb.deleteCharAt(sb.length() - 1);
} else {
return false;
}
} else if (s.charAt(i) == '}') {
if (sb.length() != 0 && sb.charAt(sb.length() - 1) == '{') {
sb.deleteCharAt(sb.length() - 1);
} else {
return false;
}
}
}
if (sb.length() == 0)
return true;
else
return false;
}
/**
* 使用栈
* Stack 因为同步,效率肯定没有LinkedList高
*/
public boolean isValid2(String s) {
LinkedList<Character> stack = new LinkedList<Character>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
stack.addFirst(ch);
} else {
if (stack.isEmpty())
return false;
char temp = stack.poll();
if (ch == ')' && temp != '(') {
return false;
} else if (ch == ']' && temp != '[') {
return false;
} else if (ch == '}' && temp != '{') {
return false;
}
}
}
if (!stack.isEmpty())
return false;
return true;
}
/**
* 使用char数组实现栈
*/
public boolean isValid3(String s) {
int maxLength = s.length() / 2 + 1;
char[] a = new char[maxLength];
int top = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '(':
case '{':
case '[':
a[top++] = s.charAt(i);
if (top >= maxLength)
return false;
break;
case ')':
if (top > 0 && a[top - 1] == '(') {
top--;
break;
}
return false;
case '}':
if (top > 0 && a[top - 1] == '{') {
top--;
break;
}
return false;
case ']':
if (top > 0 && a[top - 1] == '[') {
top--;
break;
}
return false;
default:
return false;
}
}
if (top != 0)
return false;
return true;
}
}