Leetcode[string]: Valid palindrome

Source: Internet
Author: User

given A string, determine if it is a palindrome, considering only alphanumeric characters and Igno Ring CASES. 
for example, 
" a man, a plan, a Canal:panama "  is a palindrome. 
" race a car "  is not a palindrome.

This problem is relatively simple, the general idea solution is as follows:

    BOOLIspalindrome (strings) { for(inti =0, j = s.size ()-1; I < J; ++i,--j) { while(I < s.size ()) {if(S[i] >=' 0 '&& S[i] <=' 9 ') Break;Else if(S[i] >=' A '&& S[i] <=' Z ') Break;Else if(S[i] >=' A '&& S[i] <=' Z ') {S[i] + = (' A '-' A '); Break;            } ++i; } while(J >=0)            {if(S[j] >=' 0 '&& S[j] <=' 9 ') Break;Else if(S[j] >=' A '&& S[j] <=' Z ') Break;Else if(S[j] >=' A '&& S[j] <=' Z ') {S[j] + = (' A '-' A '); Break;            }--j; }if(S[i]! = S[j])return false; }return true; }

Another solution is to use the Isalnum () and ToLower () functions in C + +. The descriptions of the two functions are as follows:

Isalnum ():


ToLower ():


The C + + solution using these two functions is as follows:

    BOOLIspalindrome (strings) { for(inti =0, j = s.size ()-1; I < J; ++i,--j) { while(I < S.size () &&!isalnum(S[i])) ++i; while(J >=0&&!isalnum(S[j])) --j;if(ToLower(S[i])! =ToLower(S[j]))return false; }return true; }

The time complexity of both methods is O (N), the spatial complexity is O (1), the time performance is similar, as shown in:


In addition, the problem can be solved using regular expressions.

Leetcode[string]: Valid palindrome

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.