问题描述
给定一个字符串,判断这个字符串是否是回文
回文的特点在于对称性,针对这个性质,笔者想到的方法有:
1)两头到中间
2)中间到两头
3)recerse前后判断
4)栈
下面,笔者将分别这四种方法用代码的形式实现
回文判断1-两头到中间
算法思想
头、尾指针分别指向字符串的首元素和尾元素,逐一比较,若有不同,则返回false,程序退出。直到头尾指针指向同一个中间元素,算法终止。时间复杂度为O(n)
两头到中间代码实现
/************************
Author:tmw
date:2017-11-13
************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool isPalindrome_edge2middle(char* array)
{
//字符串合法性检查
if(strlen(array) == 0 || array==NULL)
return false;
int front = 0;
int rear = strlen(array)-1;
while( front < rear )
{
if(array[front] != array[rear])
{
return false;
break;
}
front++;
rear--;
}
return true;
}
回文判断2-中间到两头
算法思想
- 首先对字符串进行输入合法性检查
- 在输入合法的前提下,对字符串进行操作
1)当为偶数串时,起始比较的中间数为(首+尾)/2和(首+尾)/2+1;
2)当为奇数串时,起始比较的中间数为(首+尾)/2-1和(首+尾)/2+1
算法复杂度为O(n)
中间到两头代码实现
/***********************
Author:tmw
date:2017-11-13
************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome_middle2edge(char* array)
{
//字符串合法性检查
if(array==NULL || strlen(array)==0)
return false;
//分类判断
if(strlen(array)%2!=0)//说明为奇数串
{
int front = (strlen(array)-1)/2-1;//下标从0开始
int rear = (strlen(array)-1)/2+1;
while(front>=0)
{
if(array[front]!=array[rear])
return false;
front--;
rear++;
}
}
else
{
int front = (strlen(array)-1)/2;//下标从0开始
int rear = (strlen(array)-1)/2+1;
while(front>=0)
{
if(array[front]!=array[rear])
return false;
front--;
rear++;
}
}
return true;
}
回文判断3-翻转(reverse)
算法思想
通过调用reverse函数,将原字符串翻转后与翻转前的字符串进行比较,如果相同,则是回文,反之不是。时间复杂度为O(n)
reverse代码实现
/***********************
Author:tmw
date:2017-11-13
************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define swap(x,y,t) (t=x,x=y,y=t)
bool isPalindrome_reverse(char* array)
{
//输入合法性检查
if(strlen(array)==0 || array==NULL)
return false;
char* temp;
temp = (char*)malloc((strlen(array)+1)*sizeof(char));
strcpy(temp,array);//char* strcpy(char* des,const char* source)
int front = 0;
int rear = strlen(array)-1;
while( front < rear )
{
char temp1;
swap(array[front],array[rear],temp1);
front++;
rear--;
}
if(strcmp(array,temp)==0)
return true;
else
return false;
}
回文判断4-栈(stack)
算法思想
将元素一一进栈,然后出栈,比较进栈前后是否一致,一致则为回文,不一致则不是回文。算法时间复杂度为O(n)。
算法实现
/***********************
Author:tmw
date:2017-11-13
************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool isPalindrome_stack(char* array)
{
//输入合法性判定
if(strlen(array)==0 || array==NULL)
return false;
char* stack;
stack = (char*)malloc((strlen(array)+1)*sizeof(char));
int top = 0;
for(top=0;top<strlen(array);top++)//入栈
stack[top] = array[top];
top--;//top始终指向栈顶
char* after;
after = (char*)malloc((strlen(array))*sizeof(char));//保存出栈后的字符串
int i = 0;
while(top>=0)
after[i++] = stack[top--];//出栈
after[i] = '\0';//注意!!字符串以\0结尾!否则会有乱码
free(stack);//释放栈空间
if(strcmp(array,after)==0)
return true;//栈前栈后一样,是回文,返回1
else
return false;
}
梦想还是要有的,万一实现了呢~~~ヾ(◍°∇°◍)ノ゙