📌  相关文章
📜  C 程序检查给定字符串是否为回文

📅  最后修改于: 2022-05-13 01:57:08.105000             🧑  作者: Mango

C 程序检查给定字符串是否为回文

给定一个字符串,编写 ac函数来检查它是否是回文。
如果字符串的反转与字符串相同,则称该字符串为回文。例如,“abba”是回文,但“abbc”不是回文。

回文

算法:
是回文(str)
1)找到str的长度。设长度为 n。
2)将低和高索引分别初始化为0和n-1。
3)在低索引'l'小于高索引'h'时执行以下操作。
.....a) 如果 str[l] 与 str[h] 不同,则返回 false。
.....b) 增加 l 和减少 h,即,做 l++ 和 h–。
4)如果我们到达这里,这意味着我们没有找到错误
以下是检查给定字符串是否为回文的 C 实现。

C
#include 
#include 
 
// A function to check if a string str is palindrome
void isPalindrome(char str[])
{
    // Start from leftmost and rightmost corners of str
    int l = 0;
    int h = strlen(str) - 1;
 
    // Keep comparing characters while they are same
    while (h > l)
    {
        if (str[l++] != str[h--])
        {
            printf("%s is not a palindrome\n", str);
            return;
        }
    }
    printf("%s is a palindrome\n", str);
}
 
// Driver program to test above function
int main()
{
    isPalindrome("abba");
    isPalindrome("abbccbba");
    isPalindrome("geeks");
    return 0;
}


输出
abba is a palindrome
abbccbba is a palindrome
geeks is not a palindrome