iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

刷題記錄與人生分享系列 第 4

DAY 4 Valid Parentheses

題目:

https://leetcode.com/problems/valid-parentheses/
一個字串中包含'(' , ')', '{', '}', '[' and ']',判斷字串是否迴文。

解題思路:

先放入一個字串,利用變數紀錄目前位置,如果目前其位置與放入字串為成對時繼續其步驟,但當不成對時則立即回傳錯誤。

C版本:

bool isValid(char* s) {
    char stack[1000000];
    int top=-1;
    while(*s){
        if(*s==')'){
            if(top>=0 && stack[top]=='(')top--;
            else return false;
        }else if(*s=='}'){
            if(top>=0 && stack[top]=='{')top--;
            else return false;
        }else if(*s==']'){
            if(top>=0 && stack[top]=='[')top--;
            else return false;
        }else stack[++top]=*s;
        s++;
    }
    return top==-1;
}

Javascript版本:

var isValid = function(s) {
    var stack = [];
    var top=-1;
    
    for(var i = 0; i<s.length; i++)
    {
        if(s[i] == ")")
        {
            if(top >= 0 && stack[top] == "(")
                top--;
            else
                return false;
        }
        else if(s[i] == "]")
        {
             if(top >= 0 && stack[top] == "[")
                top--;
            else
                return false;   
        }
        else if(s[i] == "}")
        {
            if(top >= 0 && stack[top] == "{")
                top--;
            else
                return false;    
        }
        else
        {
           stack[++top] = s[i];     
        }
    }
    return top==-1;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210

本日分享:

Use your smile to change the world, don’t let the world change your smile.
用你的微笑改變世界,別讓世界改變你的微笑


上一篇
DAY3 Reverse Integer
下一篇
DAY5 Remove Duplicates from Sorted Array
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言