LeetCode020 Valid Parentheses

详细见: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));
}


Python Solution: github

#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))    






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值