1. 程式人生 > >【Leetcode】【Stack】【String】Remove Duplicates from Sorted Array

【Leetcode】【Stack】【String】Remove Duplicates from Sorted Array

【20】Valid Parentheses

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

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

題譯:

給定一個只包含字元’(’,’)’,’{‘,’}’,’[‘和’]’的字串,確定輸入字串是否有效。

括號必須以正確的順序關閉,“()”和“()[] {}”都有效,但“(]”和“([]]”不是。

Solution:

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<Character>();
        for(char c : s.toCharArray()){
            if(c=='(')
                st.push(')');
            else
if(c=='{') st.push('}'); else if(c=='[') st.push(']'); else if(st.empty()||st.pop()!=c) return false; } return st.empty(); } }

心得:

1、String.toCharArray()將String轉換成char[];
2、for(char c : charArray)語法;
3、Stack的使用。