Leetcode 125. Valid palindrome-----java

Source: Internet
Author: User
Tags alphanumeric characters

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"is not a palindrome.

Note:
Are you consider that the string might is empty? This was a good question to ask during a interview.

For the purpose of this problem, we define empty string as valid palindrome.

Read whether a string is a palindrome string (only the characters and numbers in the period are judged).

1, two stacks, from front to back and back forward, and then determine whether two stacks are the same.

 Public classSolution { Public BooleanIspalindrome (String s) {Stack stack1=NewStack<character>(); Stack Stack2=NewStack<character>(); S=s.tolowercase (); Char[] Word =S.tochararray (); intLen =s.length ();  for(inti = 0;i<len;i++){            if((Word[i] >= ' 0 ' && word[i] <= ' 9 ') | | (word[i]>= ' A ' && word[i]<= ' z ') ) Stack1.push (Word[i]); if((Word[len-1-i] >= ' 0 ' && word[len-1-i] <= ' 9 ') | | (word[len-1-i]>= ' A ' && word[len-1-i]<= ' z ')) Stack2.push (Word[len-i]); }        returnstack1.equals (STACK2); }}

2, directly with two pointers to record left and right can be.

 Public classSolution { Public BooleanIspalindrome (String s) {Char[] Word =s.tolowercase (). ToCharArray (); intLen =s.length (); intleft = 0,right = Len-1;  while(Left <Right ) {            if( ! ((Word[left] >= ' 0 ' && word[left] <= ' 9 ') | | (word[left]>= ' A ' && word[left]<= ' z ')) ) left++; Else if( ! ((Word[right] >= ' 0 ' && word[right] <= ' 9 ') | | (word[right]>= ' A ' && word[right]<= ' z ' )) right--; Else if(Word[left] = =Word[right]) { Left++; Right--; }Else                return false; }        return true; }}

Leetcode 125. Valid palindrome-----java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.