1. 程式人生 > >LeetCode 20. 有效的括號(C、C++、python)

LeetCode 20. 有效的括號(C、C++、python)

給定一個只包括 '('')''{''}''['']' 的字串,判斷字串是否有效。

有效字串需滿足:

  1. 左括號必須用相同型別的右括號閉合。
  2. 左括號必須以正確的順序閉合。

注意空字串可被認為是有效字串。

示例 1:

輸入: "()"
輸出: true

示例 2:

輸入: "()[]{}"
輸出: true

示例 3:

輸入: "(]"
輸出: false

示例 4:

輸入: "([)]"
輸出: false

示例 5:

輸入: "{[]}"
輸出: true

C

bool isValid(char* s) 
{
    int n=strlen(s);
    char* temp=(char*)malloc(sizeof(char)*(n+1)/2);
    int k=0;
    for(int i=0;i<n;i++)
    {
        if(s[i]=='(' || s[i]=='[' || s[i]=='{')
        {
            temp[k]=s[i];
            k++;
        }
        else
        {
            if(k==0)
            {
                return false;
            }
            else
            {
                if(s[i]==')' && temp[k-1]!='(' || s[i]==']' && temp[k-1]!='[' || s[i]=='}' && temp[k-1]!='{' )
                {
                    return false;
                }
            }
            temp[k-1]='\0';
            k--;
        }
    }
    return strlen(temp)==0;
}

C++

class Solution {
public:
    bool isValid(string s) 
    {
        stack<char> temp;
        int n=s.length();
        for(int i=0;i<n;i++)
        {
            if(s[i]=='(' || s[i]=='[' || s[i]=='{')
            {
                temp.push(s[i]);
            }
            else
            {
                if(temp.empty())
                {
                    return false;
                }
                else
                {
                    if(s[i]==')' && temp.top()!='(' ||s[i]==']' && temp.top()!='[' || s[i]=='}' && temp.top()!='{')
                    {
                        return false;
                    }
                    temp.pop();
                }
            }
        }
        return temp.empty();
    }
};

python

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        n=len(s)
        temp=[]
        for i in range(0,n):
            if s[i]=='(' or s[i]=='[' or s[i]=='{':
                temp.append(s[i])
            else:
                if len(temp)==0:
                    return False
                elif s[i]==')' and temp[-1]!='(' or s[i]==']' and temp[-1]!='[' or s[i]=='}' and temp[-1]!='{':
                    return False
                del temp[-1]
        return len(temp)==0