1. 程式人生 > >LeetCode--Valid PalindromeⅡ

LeetCode--Valid PalindromeⅡ

實現 次數 效果 判斷 遍歷 定義 end eve str

  • 正常解法
 1 class Solution {
 2 public:
 3     bool reverse(string input)
 4     {
 5         string res="";
 6         for(int i=input.length()-1;i>=0;i--)
 7             res+=input[i];
 8         if(res==input)
 9             return true;
10         else 
11             return false;
12     }
13     bool
validPalindrome(string s) { 14 if(reverse(s)) 15 return true; 16 else 17 { 18 string copy; 19 string::iterator iter; 20 for(int i=0;i<s.length();i++) 21 { 22 copy=s; 23 iter=copy.begin();
24 copy.erase(iter+i); 25 //cout<<copy<<endl; 26 if(reverse(copy)) 27 return true; 28 29 } 30 return false; 31 } 32 33 } 34 };

以上是正常解法,但認真分析可以發現其復雜度是O(n^2),原因很簡單,首先先逐個查找去掉某一個字符的字符串是不是回文序列,查找需要n次,同時字符串與reverse後字符串的比較的次數也為n次,由此可見算法復雜度是n^2,這在leetcode上運行時會出現嚴重的超時,故采取第二種簡單的做法,可以實現O(n)復雜度。

  • 簡單做法
class Solution {
public:
    bool validPalindrome(string s) {
    int i=0,j=s.length()-1;
    int track=0;
    int si,sj;
    while(i<j)
    {
        if(s[i]==s[j])
        {
            i++;
            j--;
            continue;
        }
        if(track==2)
        {
            return false;
        }   
        if(track==1)
        {
            track++;
            i=si;
            j=sj;
            j++;
        }  
        if(track==0)
        {
            track++;
            si=i;
            sj=j;
            i--;
        }

        i++;
        j--;
    }
    return true;   
    }
};

  定義兩個標誌i,j,一個從左邊出發,一個從右邊出發,一起對比遍歷,期間有兩個選擇,可以向前退也可以向後面退,但只能一步,而且在判斷語句中,一定要把track==2放在前面實現一個判斷,不然後續判斷就沒有效果。

LeetCode--Valid PalindromeⅡ