求解南京三星电子最后一道编程大题

luyaozhi 2010-10-05 07:31:25
有两个字符串,字符串1为s1,字符串2为s2,删除字符串1中与字符串2重复的元素,并输出删除后的字符串1。
例如字符串s1为"abcdefgh1",字符串s2为"cef2h",这里输出"abdg1"。
不能创建新的字符串。
函数申明:void del(char *s1,char *s2)
...全文
184 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdu_badboy 2010-10-05
  • 打赏
  • 举报
回复
我写了一个你看看对不,不知道理解的对不对。我的思路就是外层for访问s2的每个字符,然后内层循环在s1中寻找这个字符,找到则从s1中删除.代码:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;

void del(char *s1, char *s2);

int main()
{
char s1[]="abcdefgh1";
char s2[]="cef2h";

del(s1,s2);
return 0;
}


void del(char *s1, char *s2)
{
int len2=strlen(s2);

//外层的for负责指向char *s2的每一个字符
for(int i=0; i<len2; i++)
{
char current=s2[i]; //s2的当前字符

//遍历字符串s1
for(int j=0; j<strlen(s1); j++)
{
//如果s1中找到current字符
if(s1[j]==current)
{
for(int k=j; k<strlen(s1); k++)//删除当前字符,后面字符前移
{
s1[k]=s1[k+1];
}
j--; //字符前移,所以j也后退1
}
}
}

cout<<s1<<endl;
}
GoonYangXiaofang 2010-10-05
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ayw215 的回复:]
C/C++ code

#include <iostream>
using namespace std;
void del(char *s1,char *s2)
{
char charset[256]={0};
size_t len = strlen(s2);
for (size_t i = 0 ; i < len ; ++i)
chars……
[/Quote]
++
thegreatone 2010-10-05
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstring>
void del(char *s1,char *s2)
{
while(*s2!='\0')
{
for(size_t i=0;i<strlen(s1);i++)
{
if(s1[i]==*s2)
{
for(size_t j=i;j<=strlen(s1);j++)
{
s1[j]=s1[j+1];
}
i--;
}
}
s2++;
}
}
int main()
{
char s1[]="abcdefgh1";
char s2[]="cef2h";
del(s1,s2);
std::cout<<s1<<std::endl;
return 0;
}
harderman 2010-10-05
  • 打赏
  • 举报
回复
LS的厉害
ayw215 2010-10-05
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;
void del(char *s1,char *s2)
{
char charset[256]={0};
size_t len = strlen(s2);
for (size_t i = 0 ; i < len ; ++i)
charset[s2[i]] = 1;
len = strlen(s1);
size_t index = 0;
for (size_t i = 0 ; i < len ; ++i)
charset[s1[i]]==0?s1[index++]=s1[i]:(NULL);

s1[index]=0;
cout<<s1;

}
int main()
{
char s1[]="abcdefgh1";
char s2[]="cef2h";
del(s1,s2);
return 0;
}

这种题目应该秒杀
luyaozhi 2010-10-05
  • 打赏
  • 举报
回复
忘了说,要求时间复杂度为o(n+m)!
GoonYangXiaofang 2010-10-05
  • 打赏
  • 举报
回复
一个一个删,O(n * m)
是否有更高效算法?

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧