注册 登录
编程论坛 新人交流区

求助,一个外企的面试题(c++)。。。

单调黑白 发布于 2007-10-04 16:35, 646 次点击
题目如下:
若一个字符串在中间分开后,左边与右边的反转是相同,那就是对称文字。
请写一个简单的程序函数,回传输入的字符串是否对称。
例:abcdedcba就是对称文字
9 回复
#2
coding2007-10-04 16:45
#include <iostream.h>
#include <string.h>
#include <stdio.h>
int main()
{
char szinput[30];
int nlen;
int flag=0;
cout<<"input your string:"<<endl;
cin>>szinput;
nlen=strlen(szinput)-1;
for(int i=0;i<nlen/2;i++) (不要害怕,奇偶都行)
if (szinput[i]~=szinput[nlen-i])

{ flag=1;
break;
}
if (flag==0)
cout<<"ok!"<<endl;
else
cout<<"failed"<<endl;
return 0;
}



#3
单调黑白2007-10-04 18:18
回复:(coding)#include #includ...

楼上您给出的程序 我运行后不是题中要求的样子啊。。。我把例子输入进去 "abcdedcba" 结果应该是"ok"才对啊

#4
xhtang2007-10-04 21:18



这种问题用数组应该是比较容易的,我只是写了一个可以实现的例子,我并没有考虑时间和空间的复杂度问题,你们可以作参考,其实这用动态数组是比较好的,这样比较节省空间,你们可以自己改一下,

int main()
{
char a[100];
int i=0, j, k;
char ch;
ch = getchar();
while (ch != '\n')
{
a[i] = ch;
i++;
ch = getchar();
}
j = i/2 -1;
k = i/2 +1;
while (k != i)
{
if (a[j] != a[k])
{
printf("不是回文!\n");
return 0;
}
else
{
j--;
k++;
}

}
printf("是回文! \n");
return 0;
}

#5
coding2007-10-04 21:20
对不起,应该如此
#include <iostream.h>
#include <string.h>
#include <stdio.h>
int main()
{
char szinput[30];
int nlen;
int flag=0;
cout<<"input your string:"<<endl;
cin>>szinput;
nlen=strlen(szinput)-1;
for(int i=0;i<=nlen/2;i++) (不要害怕,奇偶都行)(!!!!!!!!!!!)
if (szinput[i]~=szinput[nlen-i])

{ flag=1;
break;
}
if (flag==0)
cout<<"ok!"<<endl;
else
cout<<"failed"<<endl;
return 0;
}
#6
cj271528352007-10-04 22:11

哈哈 就这么简单

#7
nuciewth2007-10-04 22:28
重复.
#8
coding2007-10-05 12:38

//在此,我再给出一个算法,是用C++,面向对象设计的,程序有点长,对于这样一个小
//的问题也许没有必要,但是我想的是,你可以看到什么是面向对象的设计精神
//注意,我用 了MFC的库,加入了《afxwin.h>,编译时,一定要project->setting->下选择USE MFC IN A SHARED DLL

#include <iostream.h>
#include <afxwin.h>

class test
{
public:
CString str;
BOOL flag;
test();
~test();
void symmetry();
void disp();
};

test::test()
{
cout<<"input your data:"<<endl;
cin>>str.GetBuffer(200);
str.MakeUpper();
flag=TRUE;
}

test::~test()
{
}

void test::disp()
{
if (flag==TRUE)
cout<<"success"<<endl;
else
cout<<"failed!"<<endl;
}

void test::symmetry()
{

int nlen=str.GetLength()-1;
for(int i=0;i<=nlen/2;i++)
if(str.GetAt(i)!=str.GetAt(nlen-i))
{
flag=FALSE;
break;
}

}

int main()
{


test teststr;
teststr.disp();
return 0;
}

我运行了,没问题

#9
duduface2007-10-05 12:51
哇,都是高手啊,学到了很多!
#10
sunyg262007-10-05 13:44
1