Leetcode题解-5. Longest Palindromic Substring

5.  Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

思路:
1、暴力解法,从字符串的头开始,遍历所有字符,每个字符与其后面的每个字符形成L-i个子串(L为原字符串的长度,i为当前字符的位置),对每个子串进行是否是回文串的判断。结果是超时,时间复杂度是O(n^3)
bool isPalind(string s){
        for(int i = 0; i < s.size()/2; i++){
            if(s[i] != s[s.size() - i -1]) return false;
        }
        return true;
    }
    
    string longestPalindrome(string s) {
        int max = 0;
        string r;
        if(s.size() == 1) return s;
        if(s.size() == 0) return "";
        for(int i = 0; i < s.size(); i++){
            for(int k = i ; k < s.size(); k++){
                string subs = s.substr(i, k-i+1);			
                if(isPalind(subs)){
                    if(max < subs.size()){
                        r = subs;
                        max = subs.size();
                    }
                }
            }
        }
        return r;
    }

2、中心扩展法,从首字符开始进行遍历,对每个字符进行奇扩展和偶扩展,扩展的方法是一样的,都是判断左边的字符是否等于右边的字符。奇偶的区别只是在于向左向右扩展起始的位置,奇扩展是当前字符的位置,偶扩展左右位置就是当前位置和向右加一。时间复杂度是 O(n^2)
int find(string s, int left, int right){
	int n = s.size();
	while(left >=0 && right < n && s[left] == s[right]){
		left--; 
		right++;
	}
	int l = (right-1)-(left+1)+1;
	return l;
} 

string longestPalindrome(string s){
	int start = 0, max = 1;
	int n = s.size();
	for(int i = 0; i < n; i++){
		int lo = 0, le = 0;
		lo = find(s,i,i);
		if(i+1 < n) le = find(s,i,i+1);
		int cur = (lo>le) ? lo: le;
		
		if(max < cur){
			max = cur;
			if(max%2 == 0){
				start = i - (max-1)/2;
			}
			else start = i - max/2;
		}
	}
	return s.substr(start, max);
}


你可能感兴趣的:(Leetcode)