详细见:leetcode.com/problems/valid-parentheses
Java Solution: github
package leetcode;
public class P020_ValidParentheses {
public static void main(String[] args) {
// System.out.println(new Solution().isValid("([{}()])"));
// System.out.println(new Solution().isValid("()()()([)(])"));
System.out.println(new Solution().isValid(")("));
}
/*
* 1ms
* 52.87%
*/
static class Solution {
public boolean isValid(String s) {
StringBuilder st = new StringBuilder(s);
for (int i = st.length() - 1; i > 0; i --) {
if (judge(st.charAt(i - 1), st.charAt(i))) {
st.delete(i - 1, i + 1);
i = st.length();
}
}
return st.length() == 0;
}
private boolean judge(char c1, char c2) {
switch (c1) {
case '(':
if (c2 == ')')
return true;
break;
case '[':
if (c2 == ']')
return true;
break;
case '{':
if (c2 == '}')
return true;
break;
default:
break;
}
return false;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/valid-parentheses/
3ms 23.11%
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define bool int
struct stack {
char c;
struct stack * next;
struct stack * last;
};
struct stack * push_stack(char c, struct stack * stk) {
struct stack * temp = (struct stack *) malloc(sizeof(struct stack));
temp->next = NULL;
temp->last = NULL;
temp->c = c;
if (stk != NULL)
stk->next = temp;
temp->last = stk;
return temp;
};
struct stack * pop_stack(struct stack * stk) {
struct stack * last = NULL;
if (stk == NULL) return stk;
last = stk->last;
free(stk->next);
return last;
};
bool isValid(char* s) {
int i = 0, r = strlen(s);
char c = '\0', t = '\0';
struct stack * head = NULL;
for (i = 0; i < r; i ++) {
c = *(s + i);
if (c == '(') {
head = push_stack(')', head);
} else if (c == '{') {
head = push_stack('}', head);
} else if (c == '[') {
head = push_stack(']', head);
} else if (head == NULL) {
return 0;
} else {
t = head->c;
head = head->last;
if (t != c) {
return 0;
}
}
}
//ans
i = head == NULL;
//free
while (head != NULL) {
head = pop_stack(head);
}
return i;
}
int main() {
char *s = ")";
printf("answer is %d\r\n", isValid(s));
}
#coding=utf-8
'''
url: leetcode.com/problems/valid-parentheses/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年3月29日
@details: Solution: 55ms 38.66%
'''
class Solution(object):
def isValid(self, s):
sn, v = 0 if s == None else len(s), []
if sn == 0: return True
for i in range(sn):
if s[i] in {'(', '[', '{'}:
v.append(s[i])
else:
if len(v) == 0:
return False
c = v.pop()
if not c+s[i] in {"()", "[]", "{}"}:
return False
return True
if __name__ == "__main__":
s = "(]"
sol = Solution()
print(sol.isValid(s))