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.


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

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章