2020年6月20日 星期六

LeetCode 20 Valid Parentheses

  如果在程式競賽當下突然看到這一題,我應該就會用一大堆判斷式去硬解吧,不過看了提示後總算是有想法了(還是得看提示XD),Hint 1和 Hint 2 讓我覺得可以用二元搜尋樹或者Divide and Conquer解法,但是具體來說要怎麼用這兩種方式寫我還是不會,想到上次利用陣列解決回文那題就頭疼,下面C code是我參考Hint 2寫出來的,本來還想用malloc把還沒判斷的子句切出來,想想還是算了(苦笑),這個陣列元速移動方式還是我搜尋malloc,strcpy的過程中偶然發現的,感謝那篇文章的作者,ㄚㄚㄚ,這題是Easy,Hard無法想像,第14題到現在我都還卡著,可...可惡,我好笨,可是人家還是想繼續寫程式。゚ヽ(゚´Д`)ノ゚。。





Difficulty: Easy
Problem description is easy to understand, but there is lot of condition need to consider,
Fortunately, we have some example for reference.
My main idea is like hint 2, down below is C code answer.

bool isValid(char * s){
     int i,j,flag;
     int len=strlen(s);
     if(len%2!=0) return 0;
     else{
       while(len!=0){
        i=0,flag=0;
        while(i<len-1){
            j=i+1;
            if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']')||(s[i]=='{'&&s[j]=='}')){
                flag=1;
                break;
            }else{
                i+=1;
            }
        }
        if(flag==0) return flag;
        for(;j<len-1;){
            s[i]=s[j+1];
            i+=1;
            j+=1;
        }
        len-=2;
       }
     }
     return flag;
}

Reference
https://www.programmingsimplified.com/c/source-code/c-program-delete-element-from-array

沒有留言:

張貼留言

 2025 MTK 韌體工程師 上機考心得  前言: 以前, 我覺得寫前後端的人才是真正的寫程式, 很羨慕那些大神 直到這次準備, 我才發現靠杯, 原來寫底層的程式也那麼硬派, XOR 一些奇奇怪怪的加速運算操作, 剛看到真的是無法想像, 有夠虧賊!   1. C/C++ Pro...