Java Solution based on two ways to find palindromes


  • 1
    C
    public class Solution {
        public String longestPalindrome(String s) {
            String result = "";
            for(int i=0; i<s.length(); i++){
                String str = palindrome(s, i, i);
                if(result.length() < str.length())
                    result = str;
                str = palindrome(s, i, i+1);
                if(result.length() < str.length())
                    result = str;
            }
            return result;
        }
        
        String palindrome(String s, int left, int right){
        
            while(left>=0 && right<s.length() && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }
            return s.substring(left+1,right);
        }
    }

  • 1

    Marvellous solution, I tried the DP way but your solution was correct and easy to follow.


Log in to reply
 

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