herrDeng網內搜尋

自訂搜尋

Ads

2024年4月5日 星期五

python C++速解Leetcode 1544 make the string great


python C++速解Leetcode 1544 make  the string great
基本上算是stack解法,但實作的語言C, C++, python只需要善用個別字串的特性,無須使用stack,大幅加快計算速度,C語言解答請進,並加上最佳C++解
----
It is basically a stack solution, but the implementation languages ​​​​C, C++, and python only need to make good use of the characteristics of individual strings without using stack, which greatly speeds up calculations. C solution is not in the film.


#pragma GCC optimize("O3", "unroll-loops")
char* makeGood(char* s) {
    char* ans=(char*)malloc(101);//Must be dynamicall malloc
    int top=-1;
    for(register int i=0; s[i]!='\0'; i++){//strlen has O(n) TC
        if (top!=-1 && abs(s[i]-ans[top])==32)
            top--;
        else
            ans[++top]=s[i];
    }
    ans[top+1]='\0';//C-string terminal char
    return ans;
}
//最佳C++解
class Solution {
public:
    string makeGood(string& s) {
        int n=s.size(), top=-1;
        for(char c: s)
            if (top!=-1 && (c^s[top])==32)
                top--;
            else 
                s[++top]=c;
        s.resize(top+1);
        return s;
    }
};

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章