Why I got negative index in the end?


  • 0
    L
    public class Solution {
    
    public String longestPalindrome(String s) {
        if(s.length()<2){
            return s;
        }
        int finalst = 0;
        int finallen = 0;
    
        for(int i = 0; i < s.length(); i++){
            //System.out.println("loop");
            int left = i-1;
            int right = i+1;
            while(left >= 0 && right < s.length()){
                if(s.charAt(left) == s.charAt(right)){
                    left--;
                    right++;
                }else{
                    break;
                }
            }
    
            left++;
            right--;
            if((right-left+1) > finallen){
                //System.out.println(left + "--" + (right-left+1));
                finallen = right-left+1; 
                finalst = left;
            }
    
            if(i != s.length()-1 && s.charAt(i) == s.charAt(i+1)){
                left = i-1;
                right = i+2;
                while(left >= 0 && right < s.length()){
                    if(s.charAt(left) == s.charAt(right)){
                        left--;
                        right++;
                    }else{
                        break;
                    }
                }
                left++;
                right--;
                if((right-left+1) > finallen){
                   finallen = right-left+1;
                   finalst = left;
                }
            }
        }
        //System.out.println(finalst + "--" + finallen);
        if(finalst < 0 || finallen < 0){
            System.out.println(111);
        }
        String res = "" + s.substring(finalst, finallen);
        return res;
    }
    

    }


  • 0
    L

    I got negative index -27, while the finalst = 37, finallen = 7, dont understand why...


Log in to reply
 

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