Leetcode:5,https://leetcode-cn.com/problems/longest-palindromic-substring/)
给定一个字符串s,找到s中最长的回文子串。【回文串:正着读和反着读都一样】
- Input:s = "babad"
- Output:"bab"
从中心点往两边扩散,来寻找回文串,这种方式相当于穷举每一个点为中心点。若回文串是奇数,则中心点只有一个;若回文串是偶数,则中心点有两个。即先确定中心点后去找回文串,将每次找到的回文串与之前的做对比,留下最长的。
- 时间复杂度:O(n)
- 空间复杂度:O(1)
#include <iostream> #include <string> using namespace std; class Solution { public: string longestPalindrome(string s) { int len = s.size(); if (len < 2) return s; int start = 0, maxlen = 1, mid = 0; while (mid < len) { // 穷举每个中心点 int mid_start = mid, mid_end = mid; while (mid_end+1 < len && s[mid_end] == s[mid_end+1]) mid_end++; mid = mid_end+1; int left = mid_start, right = mid_end; while (left-1 >= 0 && right+1 < len && s[left-1] == s[right+1]) { left--; right++; } int curlen = right - left + 1; if (curlen > maxlen) { maxlen = curlen; start = left; } } return s.substr(start, maxlen); } }; int main() { Solution sol; string s; cin >> s; cout << sol.longestPalindrome(s) << endl; return 0; }