Valid Palindrome: Traversing from front and back simultaneously

Jay·2022년 5월 13일
0

Grind 120

목록 보기
5/38

First Thoughts: comparing first letter to last letter, if they are different, immediately returns false. If same, continue on to check the inner substring using the same method -> recursion possible. base case when length is either zero or one (return true). problem -> time complexity

My Solution:

public boolean isPalindrome(String s) {
        return checkPalindrome(makeItClean(s));
    }
    
    public String makeItClean(String s) {
        String result = "";
        for (char c : s.toLowerCase().toCharArray()) {
            if (Character.isLetterOrDigit(c)) result += c;
        }
        return result;
    }
    public boolean checkPalindrome(String s) {
        if (s.length()==1||s.length()==0) return true;
        else if (s.charAt(0)!=s.charAt(s.length()-1)) return false;
        else {
            return checkPalindrome(s.substring(1, s.length()-1));
        }
    }

Improved Solution:

for (int i=0, j=s.length()-1; i<j; i++, j--) {
	while (i<j && !Character.isLetterOrDigit(s.charAt(i)) i++;
    while (i<j && !Character.isLetterOrDigit(s.charAt(j)) j++;
    if (s.charAt(i) != s.charAt(j)) return false;
}
return true;

Catch Point

  1. There is a simpler way to check whether a character is non alphanumerical: method Character.isLetterOrDigit(ch), rather than having to compare character ascii code or use replaceAll()

  2. There is a way to simultaneously traverse the same array or string using two different variables in the same loop (declare initial value and increment/decrement separately)

0개의 댓글