LeetCode算法 —— 最長迴文子串

代碼測試已過

暫時與此題有相關思想的題目:
LeetCode算法 —— 無重複字符的最長子串

.

題目:
給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。

示例 1:
輸入: “babad”
輸出: “bab”
注意: “aba” 也是一個有效答案。

示例 2:
輸入: “cbbd”
輸出: “bb”

算法思想:將每一個數依次放入到隊列之中,然後從隊頭開始判斷是否存在子串,一直判斷找出最大的子串,代碼中都有註釋 . . .

代碼如下:

class Solution {
public:
    string longestPalindrome(string s) {
	
	// 用來標記當前最大子串的下標索引
  	int plalindrome_i = 0, plalindrome_j = 1;        
        
	int s_index(0);  // 用於索引 s
  	int count(0);  // 最長的迴文串的字符個數、用於判斷

	int* queArr(new int[s.length() + 1]); // 隊列思想
	
	int head(0), tail(0); // 隊列的頭 與 尾部
  	
  	queArr[head] = s[s_index++];   // 將第一個字符放入隊列之中
  	++tail; ++count;

	// 限制範圍、隊列滿了爲止
  	while (tail < s.length() && s_index < s.length())
  	{	
	    queArr[tail++] = s[s_index];  // 入隊

	    // 從頭開始判斷迴文子串
   	    for (size_t i = head; i < tail - 1; i++)
   	    {	
 	        // 有兩個數相同,則判斷兩個數之內建成的子串是否是迴文串
    		if (queArr[i] == s[s_index]) // 判斷要插入的數在隊列中是否有重複
    		{
    		    int flag = 0; // 用於標記是否是迴文串
     	 	    int k = 0;

		    for (size_t j = i; j < (tail - 1 + i) / 2 + 1; j++)
     		    {
      			if (queArr[j] != queArr[tail - 1 - k++]) {  // 判斷是不是迴文子串
       			    flag = 1;
       			    break;
      		    	}
     		    }

		    // 是迴文串、並且比上次的迴文串長
     		    if (!flag && count < tail - i)  
     		    {
      			count = tail - i;  
      			plalindrome_i = i;
      			plalindrome_j = tail;
      			
      			break;
     		    }
    		}

   	    }

	    ++s_index;
  	}

	// 獲取最長的迴文子串
  	string str(s.begin() + plalindrome_i, s.begin() + plalindrome_j);
  
  	return str;
    }
};

測試代碼:

cout << (new Solution())->longestPalindrome("a") << endl << endl;
cout << (new Solution())->longestPalindrome("abcda") << endl << endl;
cout << (new Solution())->longestPalindrome("ccc") << endl << endl;
cout << (new Solution())->longestPalindrome("bb") << endl << endl;
cout << (new Solution())->longestPalindrome("babad") << endl << endl;
cout << (new Solution())->longestPalindrome("abcccbamm") << endl << endl;
cout << (new Solution())->longestPalindrome("huamenggnemauhmm") << endl << endl;
cout << (new Solution())->longestPalindrome("aaabaaaa") << endl << endl;

結果如下:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章