2025年3月19日 星期三 甲辰(龙)年 月十八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

字节跳动刷题 字符串处理&vector

时间:03-30来源:作者:点击数:70

我叫王大锤,是一家出版社的编辑。我负责校对投稿来的英文稿件,这份工作非常烦人,因为每天都要去修正无数的拼写错误。但是,优秀的人总能在平凡的工作中发现真理。我发现一个发现拼写错误的捷径:

  1. 三个同样的字母连在一起,一定是拼写错误,去掉一个的就好啦:比如 helllo -> hello
  2. 两对一样的字母(AABB型)连在一起,一定是拼写错误,去掉第二对的一个字母就好啦:比如 helloo -> hello
  3. 上面的规则优先“从左到右”匹配,即如果是AABBCC,虽然AABB和BBCC都是错误拼写,应该优先考虑修复AABB,结果为AABCC

我特喵是个天才!我在蓝翔学过挖掘机和程序设计,按照这个原理写了一个自动校对器,工作效率从此起飞。用不了多久,我就会出任CEO,当上董事长,迎娶白富美,走上人生巅峰,想想都有点小激动呢!

……

万万没想到,我被开除了,临走时老板对我说: “做人做事要兢兢业业、勤勤恳恳、本本分分,人要是行,干一行行一行。一行行行行行;要是不行,干一行不行一行,一行不行行行不行。” 我现在整个人红红火火恍恍惚惚的……

请听题:请实现大锤的自动校对程序

输入描述:

第一行包括一个数字N,表示本次用例包括多少个待校验的字符串。

后面跟随N行,每行为一个待校验的字符串。

输出描述:

N行,每行包括一个被修复后的字符串。

输入例子1:

2

helloo

wooooooow

输出例子1:

hello

woow

考验的是字符串处理能力,那么第一时间会考虑的是,使用指针,从第一个元素开始,对比与它相邻的元素,若发现错误,则对某个元素进行处理,那么至少要使用到3个指针,这种方法无疑是较为复杂的。第二种方法,我们可以建立两个字符串数组,一个出,一个进,把好进的关口,对于出现的错误忽略,正确的进入,第一种代码实现较为暴力,第二种使用vector。

  • #include <stdio.h>
  • #include <string>
  • #include <iostream>
  • #include<bits/stdc++.h>
  • using namespace std;
  • int main()
  • {
  • int n;
  • scanf("%d", &n);
  • while(n--)
  • {
  • char str1[1000];
  • cin>>str1;
  • int len1 = strlen(str1);
  • char str2[1000] = {};
  • int len2 = strlen(str2);
  • int j = 0;
  • for(int i=0;i<len1;i++)
  • {
  • int len2 = strlen(str2);
  • if(len2 < 2)
  • {
  • str2[j++] = str1[i];
  • //printf("j=%d\n", j);
  • continue;
  • }
  • if(len2 >= 2)
  • {
  • int a = j - 1;
  • int aa = j - 2;
  • if(str1[i]==str2[a] && str1[i]==str2[aa])
  • {
  • continue;
  • }
  • }
  • if(len2 >=3)
  • {
  • int a = j-1;
  • int aa = j-2;
  • int aaa = j-3;
  • if(str2[aaa]==str2[aa] && str2[a]==str1[i])
  • {
  • continue;
  • }
  • }
  • str2[j++] = str1[i];
  • }
  • len2 = strlen(str2);
  • //printf("长度%d\n",len2);
  • for(int k=0;k<len2;k++)
  • {
  • printf("%c", str2[k]);
  • }
  • printf("\n");
  • }
  • return 0;
  • }
  • #include <iostream>
  • #include <bits/stdc++.h>
  • #include<iterator>
  • #include<vector>
  • using namespace std;
  • int main()
  • {
  • int n;
  • scanf("%d", &n);
  • while(n--)
  • {
  • string res;
  • cin>>res;
  • vector<char>str;
  • for(int i=0;i<res.length();i++)
  • {
  • vector<char>::iterator v;
  • if(str.size()<2)
  • {
  • str.push_back(res[i]);
  • continue;
  • }
  • if(str.size()>=2)
  • {
  • v = str.end() - 1;
  • char a = *v;
  • v--;
  • char aa = *v;
  • if(res[i]==a && res[i]==aa)
  • {
  • continue;
  • }
  • }
  • if(str.size()>=3)
  • {
  • v = str.end() - 1;
  • char a = *v;
  • v--;
  • char aa = *v;
  • v--;
  • char aaa = *v;
  • if(res[i]==a && aa==aaa)
  • {
  • continue;
  • }
  • }
  • str.push_back(res[i]);
  • }
  • vector<char>::iterator vv;
  • for(vv=str.begin();vv!=str.end();vv++)
  • {
  • cout<<*vv;
  • }
  • cout<<endl;
  • }
  • return 0;
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门