A simple O(n) time and space java solution using iteration


  • 0
    G
    public class Solution {
        public boolean isPalindrome(String s) {
            boolean flag = true;
            String str = s.toLowerCase().replaceAll("[^a-z0-9]","");
            for(int i=0; i<str.length()/2; i++){
                if(str.charAt(i) != str.charAt(str.length()-1-i)){
                    flag = false;
                }
            }
            return flag;
        }
    }

  • 0
    D

    As soon as you find two characters that don't match you should return false. No need to continue checking the rest of the string.


  • 0

    i agree with the first floor, so u can add "break" behind "flag = false",but ur idea is really good.


Log in to reply
 

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