My accepted solution in JAVA, which is concise I think


  • 4
    V

    The point is knowing how to use replaceAll() method in String class.... take me a while to learn the pattern argument.

    public class Solution {
        public boolean isPalindrome(String s) {
            s = s.toLowerCase(); // convert all to lower cases.
            s = s.replaceAll("[^a-z^0-9]+", ""); // remove all non-digital and non-letter.
            int len = s.length();
            for (int i = 0; i < len; i++){
                if (s.charAt(i) != s.charAt(len - i - 1)){
                    return false;
                }
            }
            return true;
       }
    }

  • 0
    L

    It is concise and elegant. But probably not the most efficient, since the string pattern matching probably needs to traverse the entire string one more time.


  • 0
    M

    do u you know an elegant method to traverse the string in c++?


  • 0
    L

    What I meant is that you could also put the checking of non-alphanumeric characters in the loop of switching, in that case you need to go over the string for once.


  • 0
    A

    Instead loop the entire string, you can loop only half of it, thus len/2 instead of len.


Log in to reply
 

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