[Java] Time Limit Exceeded with long string , anyhelp????


  • 0
    W
    public class Solution {
    public boolean isPalindrome(String s) {
       boolean isPalindrome = true;
        if (s!=null&&s.length()!=0) {
            String testString = "";
            for (int i = 0; i < s.length(); i++) {
                if (Character.isLetterOrDigit(s.charAt(i))) {
                    testString += Character.toLowerCase(s.charAt(i));
                }
            }
            if(testString!=null&&testString.length()!=0){
            int i = 0;
            int j = testString.length() - 1;
            while(i < j){
                 if (testString.charAt(i) != testString.charAt(j)) {
                    isPalindrome = false;
                    break;
                }
                i++;
                j--;
            }
                
            }
    
               
            
        }
    
    
        return isPalindrome;
    }
    

    }


  • 0
    L

    generate the char array( char[]) first, then access the char with Subscript, rather then use charAt()


  • 0
    F

    because "string1 += string2" which also named concatenation itself is a O(n^2) complexity. You should change your textString into "StringBuffer" or char[]


Log in to reply
 

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