LeetCode(C语言) - 125. 验证回文串

https://leetcode.cn/problems/valid-palindrome/submissions/

提交代码

思路:对撞指针

int toChar(char ch){
    if(ch>='0'&&ch<='9'){
        return ch;
    }else if(ch>='A'&&ch<='Z'){
        return ch - 'A' + 'a';
    }else if(ch>='a'&&ch<='z'){
        return ch;
    }else{
        return 0;
    }
}
bool isPalindrome(char * s){
    int left=0,right;
    int i;
    for(i=0;s[i]!='\0';i++){}
    right = i;
    while(left<right){
        if(toChar(s[left])==0){
            left++;
        }
        if(toChar(s[right])==0){
            right--;
        }
        if(toChar(s[left])&&toChar(s[right])){
            if(toChar(s[left])==toChar(s[right])){
                left++;
                right--;
            }else{
                return 0;
            }
        }
    }
    return 1;
}

执行结果

执行结果:
通过
显示详情
添加备注

执行用时:
4 ms
, 在所有 C 提交中击败了
70.17%
的用户
内存消耗:
6.1 MB
, 在所有 C 提交中击败了
67.68%
的用户
通过测试用例:
480 / 480

完整代码

#include <stdio.h>
int toChar(char ch){
    if(ch>='0'&&ch<='9'){
        return ch;
    }else if(ch>='A'&&ch<='Z'){
        return ch - 'A' + 'a';
    }else if(ch>='a'&&ch<='z'){
        return ch;
    }else{
        return 0;
    }
}
bool isPalindrome(char * s){
    int left=0,right;
    int i;
    for(i=0;s[i]!='\0';i++){}
    right = i;
    while(left<right){
        if(toChar(s[left])==0){
            left++;
        }
        if(toChar(s[right])==0){
            right--;
        }
        if(toChar(s[left])&&toChar(s[right])){
            if(toChar(s[left])==toChar(s[right])){
                left++;
                right--;
            }else{
                return 0;
            }
        }
    }
    return 1;
}

main(){
//	char ch[] = "aaaa";
//	char ch[] ="amanaplanacanalpanama";
//    char ch[] = "A man, a plan, a canal: Panama";
    char ch[] = "race a car";
	
    bool res = isPalindrome(ch);
    if(res){
        printf("true");
    }else{
        printf("false");
    }
}

控制台输出

false
--------------------------------
Process exited after 0.3994 seconds with return value 0
请按任意键继续. . .
posted @ 2022-05-15 23:14  孤舟浮岸  阅读(87)  评论(0)    收藏  举报