Java solution using Stack, easy to understand


  • -1
    L

    import java.util.Stack;
    public class Solution {

    public boolean isPalindrome(String s) {
            if (s.equals(""))
            return true;
            else {
                //put the whole string into a stack
                char[] str = s.toCharArray();
                Stack palinStack = new Stack();
                for (char c: str) {
                    if (Character.isLetterOrDigit(c)) {
                    palinStack.push(Character.toLowerCase(c));
                    }
                }
                
                //pop it out and compare each of the character with the original one
                for (int i = 0; i<s.length(); i++) {
                	if (Character.isLetterOrDigit(s.charAt(i))) {
                		char c = Character.toLowerCase(s.charAt(i));
                		if ((Character) palinStack.pop() != c)
                			return false;
                	}
                }
                if (palinStack.isEmpty())
                	return true;
                else
                	return false;
            }
      
    }
    

    }


Log in to reply
 

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