c++ - Valid palindrome OJ -
given string, determine if palindrome, considering alphanumeric characters , ignoring cases. example, "a man, plan, canal: panama" palindrome. "race car" not palindrome.
class solution { public: bool ispalindrome(string s) { if (!s.length()) homecoming true; int = 0, j = s.length() - 1; (int k = 0; k < j; ++k) s[k] = tolower(s[k]); while (i < j) { if ((s[i] < 48)||(s[i] > 57 && s[i] < 97)||(s[i] > 122)) ++i; else if ((s[j] < 48)||(s[j] > 57 && s[j] < 97)||(s[j] > 122)) --j; else if (s[i++] != s[j--]) homecoming false; } homecoming true; } }; wrong answer: input: "!bhvx!?!!vhbx" output: true expected: false what's wrong it?
you never convert lastly character lower case because loop status k < j , j index of lastly character. alter loop to:
for (int k = 0; k <= j; ++k) s[k] = tolower(s[k]); also, code easier read if used character constants such 'a' instead of ascii codes.
c++ string
No comments:
Post a Comment