字符串-------最长回文串(leetcode5)

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

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

自己写的 效率不是很好

import java.util.HashMap;
public class Solution {
    public String longestPalindrome(String s) {
		//key:长度 vlaue:该长度对应的字符串
        HashMap<Integer, String> map=new HashMap<Integer, String>();
		
    	int max=0;
        //i 起始点 j结束点
		for(int i=0;i<s.length();i++)
		{
			for(int j=i;j<s.length();j++)
			{
				//判断是否为回文串
                if(isPalindrome(s, i, j))
					//判断该回文串长度是否最大
                    if((j-i+1)>=max)
					{
						max=(j-i+1);
						String str=s.substring(i, j+1);
						//把当前最长的字符串存进map
                        map.put(max, str);
					}
					
			}
		}
		//取出最长的字符串
    	return map.get(max);
        
    }
    public boolean isPalindrome(String s,int st,int end) {
		while(st<end)
		{
			if(s.charAt(st++)!=s.charAt(end--))
				return false;
		}
    	return true;
    }
}


猜你喜欢

转载自blog.csdn.net/ustcyy91/article/details/80113833