判断是否是回文字符串

要求

判断是否是回文字符串

做法

先将字符串转化为小写字符串,接着初始化一个头指针和尾指针,遍历字符串,遍历的时候注意字符是否是‘1’~‘9’或‘a’~‘z',如果不是就跳过遍历。如果头尾指针遍历到的字符不同就返回false,否则继续遍历。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace::std;
class Solution {
public:

  /**
 * 判断是否是1~9或a~b之中的字符
 **/
    bool isNormalChar(char c){
        if (('a'<=c&&c<='z')||('0'<=c&&c<='9')) {
            return true;
        }
        return false;
    }

    bool isPalindrome(string s) {
        if (s.length()<=1) {
            return true;
        }
        //将字符串中的大写转化为小写
        transform(s.begin(), s.end(), s.begin(),::tolower);
        int n = (int)s.length();
        int i = 0;
        int j = n-1;
        while (i<j) {
            if (s[i]==s[j]) {
                i++;
                j--;
            }else{
                if (!isNormalChar(s[i])) {
                    i++;
                }else if(!isNormalChar(s[j])){
                    j--;
                }else{
                    return false;
                }
            }
        }
        return true;
    }
};
int main(int argc, const char * argv[]) {
    Solution* s = new Solution();
    cout<<s->isPalindrome("ab")<<endl;
    return 0;
}

Comments