Weird problem of while loop, plz help


  • 0
    M

    the following is my solution, basically using arrays and check first letter and the last letter of every possible solutions. the comment part is the cause of wrong output, it throws me the right answer if I do not have the inner while loop.
    please help! thanks a lot!

    public String longestPalindrome(String s) {
        if(s == null) return "";
        if(s.length() == 1) return s;
        char[] c = s.toCharArray();
        Map<Integer,char[]> store = new HashMap<>();
        for(int i =0; i < c.length - 1; i++){
            for(int j = c.length - 1; j > i; j--){
               //trouble here!!!
               //while(c[i] != c[j] && j > i){
                  //  j--;
               // }
                char[] temp = Arrays.copyOfRange(c,i,j);
                if(check(temp)){ store.put(j-i,temp);
                break;}
            }
        }
        return new String(store.get(Collections.max(store.keySet())));
    }
    
    public boolean check(char[] temp){
        for(int i = 0; i<temp.length/2 - 1; i++){
            if(temp[i] != temp[temp.length -1 - i])
            return false;
        }
        return true;
    }

Log in to reply
 

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