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.
Main topic:
Test of Palindrome.
Ideas:
1. Clean the string and get the string with only numbers and letters.
2. Judge by comparing the characters to the end.
Class solution {public: vector<string> stringsplit (String s, const char * split) { vector<string> result; const int slen = s.length (); char *cs = new char[slen + 1]; strcpy (Cs, s.data ()); char *p; p = strtok (CS, split); while (p) { printf ("%s \ n ", p); string tmp (P); result.push_back (TMP); p = strtok (Null, split); } Return result; } bool ispalindrome (String s) { if (s.size () == 0 | | s.size () == 1) return true; vector< String> vecstrs = stringsplit (S, " [email protected]#$%^&* ().,:;-?\" "); s = ""; for (int i = 0; i < vecstrs.size (); i++) s += vecStrs[i]; if (s.size () == 1 | | s.size () == 0) return true; int i = 0; for (; i < s.size () / 2; i++) { if (s[i] <= 57 | | s[s.size () - i - 1] <= 57) { if (S[i] == s[s.size () - i - 1]) { continue; } else { return false; } } else if (S[i] == s[s.size () - i - 1] | | s[i] - s[s.size () - i - 1] == 32 | | s[s.size () - i - 1] - s[i] == 32) { continue; } else { return false; } } return true; }};
The above approach is inefficient and unfamiliar to the API.
Here are the improvements to the above:
Reference https://discuss.leetcode.com/topic/48376/12ms-c-clean-solution
The code is as follows:
Class Solution {Public:bool Ispalindrome (string s) {int i = 0, j = s.size ()-1;while (I < J) {while (!isalnum (S[i]) &am p;& i < J) I++;while (!isalnum (s[j]) && i < J) J--;if (ToLower (s[i++])! = ToLower (s[j--])) return false; return true;}};
Here, the isalnum () function is used to determine whether a literal number.
By using ToLower () to unify the case of a character, it becomes lowercase.
2016-08-11 13:26:25
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1836839
Leetcode 125. Valid palindrome String