[英]C++ Palindrome Bool Function (Using Pointer)
如何在C ++中創建回文函數? 我正在使用2個函數類型(bool和void)。 到目前為止,這是我的代碼(非常感謝您的幫助,為什么我的代碼無法正常工作?)謝謝!
#include <iostream>
#include <cctype>
#include <cstdlib>
#include <string>
using namespace std;
void reverse(char *);
bool isPalindrome(char *);
int main()
{
char a[10];
cout << "string ";
cin.getline(a, 10);
if (palindrome(a))
cout << "true";
else
cout << "false";
return 0;
}
void reverse(char *s)
{
char *point = s;
int i, min;
for (i = 0; *point != '\0'; i++)
point++;
min = i;
point--;
for (i = min; i > 0; i--)
{
cout << *point--;
}
}
bool ispalindrome(char *s)
{
bool status;
char *original = s;
char *point = s;
reverse(point);
for (int i = 0; point != '\0'; i++)
{
if (point[i] == original[i])
status = true;
else
status = false;
}
return status;
}
這里有幾處可以改進的地方。 您最直接的問題是isPalindrome
函數中的for循環不會終止。 將終止條件更改為point[i] != '\\0'
。
其次,反向功能實際上並未反向。 如果要使用此算法,則需要為反向字符串分配內存。 不過,更好的方法是將指針放在字符串的開頭,將指針放在字符串的末尾,然后將它們移到字符串的中間。
您無需反轉字符串即可檢查其回文。
該算法的工作原理如下:
獲取字符串的長度;
從零到字符串的長度乘以2;
將位置循環計數的字符與長度減去循環計數減去1進行比較;
如果不相等,則不是回文;
如果循環結束,則為回文;
例如:“測試”:
第一步:將“ t”與“ t”進行比較
第二步:將“ e”與“ s”進行比較->而不是回文
例如“ palap”:
第一步:將“ p”與“ p”進行比較
第二步:將“ a”與“ a”進行比較
第三步:將“ l”與“ l”進行比較
現在我們知道這是一個回文。
試試這個:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int palindrom(char * s){
int i;
int l = strlen(s);
for(i=0;i<=l/2;i++)
if(s[i]!=s[l-i-1]) return 0;
return 1;
}
int main(void) {
char * test = "test";
char * pal = "palap";
printf("%s %d", test, palindrom(test));
printf("%s %d", pal, palindrom(pal));
return 0;
}
類似於@linluk的使用指針而不是索引的答案...
#include <cstring>
bool palindrome(char *s)
{
for (char *e = strchr(s, '\0'); -- e > s; ++ s)
if (*e != *s)
return false;
return true;
}
最初, e
指向字符串的結尾,而s
指向字符串的開頭。 在每次迭代中, e
向后退,而s
向前進,直到它們在中間相遇。 如果他們指向彼此不同的字符,則測試失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.