My C++ solution


  • 0
    L
    class Solution {
    public:
        string longestPalindrome(string s) {
        	if (s.size() <= 2) return s;
        	int maxlen = 0;
        	int start, end;
        	int bstart, bend;
        	int temp = 0;
        	for (int i = 1; i <= s.size() - 1; i++)
        	{
        		start = i - 1;
        		end = i;
        		temp = 0;
        		while ((start >= 0) && (end <= s.size() - 1) &&(s[start] == s[end]) )
        		{
        			start--;
        			end++;
        		}
        		temp = end - start + 1;
        		if (temp > maxlen)
        		{
        			maxlen = temp;
        			bstart = ++start;
        			bend = --end;
        		}
        		start = i - 1;
        		end = i + 1;
        		temp = 0;
        		while ((start >= 0) && (end <= s.size() - 1) && (s[start] == s[end]) )
        		{
        			start--;
        			end++;
        		}
        		temp = end - start + 1;
        		if (temp > maxlen)
        		{
        			maxlen = temp;
        			bstart = ++start;
        			bend = --end;
        		}
        	}
        	return s.substr(bstart, bend-bstart+1);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.