代码改变世界

Valid Palindrome

2015-03-16 15:32  笨笨的老兔子  阅读(128)  评论(0编辑  收藏  举报

判断一个字符串是否是对称的

跳过所有非数字和字母,字母不分大小写

  • 知道函数isalnum和tolower或者toupper就可以做了,两个指针一个指向头,一个指向尾,朝中间靠拢比较
  • 空串是对称的

    1. class Solution {
    2. public:
    3. bool isPalindrome(string s) {
    4. if (s.empty())
    5. {
    6. return true;
    7. }
    8. int head = 0,tail=s.size()-1;
    9. while (head < tail)
    10. {
    11. if (isalnum(s[head]) && isalnum(s[tail]))
    12. {
    13. if (tolower(s[head]) == tolower(s[tail]))
    14. {
    15. head++; tail--;
    16. }
    17. else
    18. {
    19. return false;
    20. }
    21. }
    22. if (!isalnum(s[head]))
    23. {
    24. head++;
    25. }
    26. if (!isalnum(s[tail]))
    27. {
    28. tail--;
    29. }
    30. }
    31. return true;
    32. }
    33. };