python C++速解Leetcode 1544 make the string great
----
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;
}
};
沒有留言:
張貼留言