可以使用双指针的方法,从字符串的两端开始往中间遍历,如果对应的字符相同,则继续比较下一个字符,直到两个指针相遇或者跨过了中间点。如果在这个过程中有任何一组对应的字符不相同,就说明这个字符串不是回文。

具体实现如下:

#include <stdio.h>
#include <string.h>

int isPalindrome(char *s) {
    int len = strlen(s);
    int i = 0, j = len - 1;
    while (i < j) {
        if (s[i] != s[j]) {
            return 0;
        }
        i++;
        j--;
    }
    return 1;
}

int main() {
    char s[100];
    printf("Please enter a string: ");
    scanf("%s", s);
    if (isPalindrome(s)) {
        printf("This string is a palindrome.\n");
    } else {
        printf("This string is not a palindrome.\n");
    }
    return 0;
}

注意,这个算法只能判断正读和反读完全相同的回文字符串,如果是忽略大小写或者忽略空格的回文字符串,需要对字符串进行预处理。


原文地址: http://www.cveoy.top/t/topic/bzub 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录