#include<iostream>//C++版
//判断是否包含回文字符串,如有,返回回文起始位置;如没有,返回字符串长度
using namespace std;
int find(char ch,char *str,size_t length) //查找str开始的字符串中第一个ch出现的位置,没找到返回-1
{
for(int i=0;i<length;i++)
{
if(ch == str[i])
return i;
}
return -1;
}
int isSym(char *str,size_t length) //判断一个字符串是否全对称,0对称,-1不对称
{
for(int i=0;i<length/2;i++)
{
if(str[i] != str[length-i-1])
return -1;
}
return 0;
}
int isSymmetry(char *str,size_t length)//返回原字符串长度表示全部对称,-1表示无对称,其他值表示局部对称起始位置
{
if (isSym(str, length) == 0)
{
return length;
}
int begin=0,end;
char ch;
for(int i=0;i<length;i++)
{
ch = str[i];
begin = end = i;
while((begin = find(ch,str+end+1,length-end-1)) != -1)
{
end = begin+end+1;
if(isSym(str+i,end-i+1) == 0)
return i;
}
}
return -1;
}
int main()
{
char aa1[] = "123454321";
char aa2[] = "123456547890";
char aa3[] = "781234327891";
char aa4[] = "954612313217891";
char aa5[] ="3093166233266908312``";
cout<<isSymmetry(aa1,sizeof(aa1)/sizeof(char)-1)<<endl;
cout<<isSymmetry(aa2,sizeof(aa2)/sizeof(char)-1)<<endl;
cout<<isSymmetry(aa3,sizeof(aa3)/sizeof(char)-1)<<endl;
cout<<isSymmetry(aa4,sizeof(aa4)/sizeof(char)-1)<<endl;
cout<<isSymmetry(aa5,sizeof(aa5)/sizeof(char)-1)<<endl;
return 0;
}
转载自:http://www.cnblogs.com/mingzi/archive/2009/08/04/1538418.html
java版:
public class HuiWen{
public static void main(String[]args){
String str="987098321123211980890";
HuiWen h=new HuiWen();
int k=h.isOrNot(str);
System.out.println(k);
}
public static int isOrNot(String str){
char []A=str.toCharArray();
int index;
for(int i=0;i<A.length;i++){
char t=A[i];
if((index=find(A,t,i+1,A.length-1))!=-1){
if(allOk(A,i,index)!=-1){
return i;
}
}
}
return A.length;
}
public static int find(char A[],char x,int lo,int hi){
int i=0;
for(i=lo;i<=hi;i++){
if(A[i]==x){
return i;//找到输出下标
}
}
return -1;//未找到,输出-1
}
public static int allOk(char A[],int lo,int hi){//判断整个字符串是否是回文
int k=0;
int i;
for(i=lo;i<=hi;k++,i++){
if(A[i]!=A[hi-k]){
return -1;
}
}
return 1;
}
}