Java solution using stack (28 ms)


  • 0
    L
    public boolean isPalindrome(String s) {
    	Stack<Character> stack = new Stack<>();
    
    	for (char c : s.toLowerCase().toCharArray()) {
    		if (Character.isLetterOrDigit(c)) {
    			stack.add(c);
    		}
    	}
    	if (stack.size() < 2) {
    		return true;
    	}
    
    	for (char c : s.toLowerCase().toCharArray()) {
    		if (Character.isLetterOrDigit(c) && c != stack.pop()) {
    			return false;
    		}
    	}
    
    	return stack.isEmpty();
    }
    

Log in to reply
 

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