validPalindrome

This is an example guo has talked about in the class. There are something to keep in mind.

  1. Start Simple! After solve the simplest case, add boundaries.
  2. in this case, two pointers is better, because we need to ignore the non digit and characters case.
  3. YOU REALLY NEED TO RUN THE CODE WITH A TEST CASE ON A PAPER OR IN YOUR MIND FIRST, NO MATTER HOW SIMPLE IT IS.
  4. While using the s.length(), think about you are using it for an index or the length.
public class Solution {
    /**
     * @param s A string
     * @return Whether the string is a valid palindrome
     */
    public boolean isPalindrome(String s) {
        // Write your code here
        int i = 0;
        // here must be s.length() - 1! You should keep this in mind: are you using a length or a index?
        int j = s.length() - 1;
        String str = s.toUpperCase();

        while (j > i) {
            if (!Character.isLetterOrDigit(str.charAt(i))) {
                i++;
                continue;
            }
            if (!Character.isLetterOrDigit(str.charAt(j))) {
                j--;
                continue;
            }
            if (str.charAt(i) != str.charAt(j)) {
                return false;
            }
            // here is a large problem!
            i++;
            j--;
        }
        return true;
    }
}