https://leetcode.com/problems/valid-palindrome/
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.
- String problem. Two methods, one is to directly compare string flip, the other is the traditional two pointer movement comparison.
- Learned the string-related STL algorithms and functions, adding char to a string with push_back.
- Toupper-c++ Reference
- http://www.cplusplus.com/reference/cctype/toupper/
- Isalnum-c++ Reference
- Http://www.cplusplus.com/reference/cctype/isalnum/?kw=isalnum
- Transform-c++ Reference
- Http://www.cplusplus.com/reference/algorithm/transform/?kw=transform
- String::p ush_back-c++ Reference
- http://www.cplusplus.com/reference/string/string/push_back/
- Reverse_copy-c++ Reference
- http://www.cplusplus.com/reference/algorithm/reverse_copy/
- Reverse_copy
- Https://msdn.microsoft.com/zh-cn/library/c7ty5c36.aspx
1#include <iostream>2#include <string>3#include <cctype>//ToUpper, Isalnum4#include <algorithm>//Transform5 using namespacestd;6 7 classSolution {8 Public:9 BOOLIspalindrome (strings)Ten { One stringStemp ="", Sreverse =""; A - //Convert characters to UPPER - transform (S.begin (), S.end (), S.begin (),:: ToUpper); the - //considering only alphanumeric characters - for(inti =0; I < s.length (); i + +) - if(Isalnum (s.at (i))) +Stemp.push_back (s.at (i));//appends character to the end of the string, increasing it length by one. - + //need to allocate space if use reverse_copy A sreverse.resize (Stemp.length ()); at reverse_copy (Stemp.begin (), Stemp.end (), Sreverse.begin ()); - /* - sreverse = stemp; - Reverse (Sreverse.begin (), Sreverse.end ()); - */ - /* in cout << stemp << Endl; - cout << sreverse << Endl; to */ + returnStemp = =Sreverse; - } the * BOOLIsPalindrome2 (strings) $ {Panax Notoginseng intStart =0, end = S.length ()-1; - the while(Start <end) + { A if( !isalnum (s.at (start))) theStart + +; + Else if( !isalnum (s.at (end))) -End--; $ Else if(ToUpper (s.at (start))! = ToUpper (s.at (end)))//Remember ToUpper $ return false; - Else - { the //Remember to move ptr -Start + +;WuyiEnd--; the } - } Wu - return true; About } $ - }; - - intMain () A { + solution testsolution; the stringStest[] = {"a man, a plan, a Canal:panama","Race a car"}; - $ for(inti =0; I <2; i + +) thecout << testsolution.ispalindrome (stest[i]) <<Endl; the the GetChar (); the - return 0; in}
View Code
Leetcode 125. Valid palindrome