conchincradle / leetcode

0 stars 0 forks source link

01.String #1

Open conchincradle opened 2 years ago

conchincradle commented 2 years ago

200 · 最长回文子串

public String longestPalindrome(String s) {
        // write your code here
        int start = 0, end = 0;
        int max = 0;
        for(int i=0; i<s.length()-1;++i){
            int len1 = expand(s,i,i);
            int len2 = expand(s,i,i+1);
            int len = Math.max(len1,len2);
            if(len>end-start){
                start = i-(len-1)/2; // 3 or 4 is both -1
                end = i+len/2;   // 3 is +1 4 is + 2
            }

        }
        return s.substring(start, end+1);

    }
    private int expand(String s, int left, int right){
        while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)){
            left--;
            right++;
        }
        return right-left-1;

    }

odd and even condition is easy to decide by an example, e.g 3 -- left should be i -1, right should be i + 1 4 -- left should be i-1, right should be i + 2 so left should be i-len-1/2, right should be i + len/2

and two conditions, s[i] and s[i+1] aba, abba and the s[len-1] only have itself, so i is 0->len-2 is enough

and start , end represent the first and the final position but left and right represent the pointer next to them