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;

结果如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42100963/article/details/106463340