My Java Solution easy to understand beats 99.37% solutions


  • 0
    C

    public class Solution {
    public String longestPalindrome(String s) {
    int length = 0;
    int start = 0;
    int end= 0;
    char[]ch = s.toCharArray();
    for(int i=0;i<ch.length;i++)
    {
    if(isPalindrome(ch,i-length-1 , i))
    {
    start = i-length-1;
    end = i;
    length += 2;
    }
    else if(isPalindrome(ch, i-length, i))
    {
    start = i-length;
    end = i;
    length += 1;
    }
    }
    return s.substring(start, end+1);
    }

    public boolean isPalindrome(char[]ch, int start, int end)
    {
    if(start<0)
    return false;
    while(start<end)
    {
    if(ch[start++]!=ch[end--])
    return false;
    }
    return true;
    }
    }


Log in to reply
 

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