您的位置:首页 > 理论基础 > 数据结构算法

字符串-拼写检查(数据结构基础 第4周)

2016-07-06 09:42 435 查看
问题描述





分析

题目不算难,但注意容易时间复杂度,容易超吃。

源码

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cstdio>
using namespace std;

int issimilar(string a, string b) {
if (a.length() == b.length()){
int counts=0;
for (int i=0; i<b.length(); i++){
if (a.at(i)!=b.at(i)) {
counts++;
}
}
if (counts==0){
return 2;
}
else if(counts==1){
return 1;
}
}
if (a.length()-b.length() == 1) {
int j=0;
int counts=0;
for(int i=0 ; i<b.length(); i++, j++) {
if (b.at(i) != a.at(j)) {
i--;
counts++;
if (counts > 1) {
return 0;
}
}
}
return 1;
/*
for (int i=0; i<a.length(); i++) {
if (b==(a.substr(0, i)+a.substr(i+1))) {   //使用此操作会超时
return 1;
}
}
*/
}
if (b.length()-a.length() == 1) {
int j=0;
int counts=0;
for(int i=0; i<a.length(); i++, j++) {
if (a.at(i) != b.at(j)) {
i--;
counts++;
if (counts > 1) {
return 0;
}
}
}
return 1;
/*
for (int i=0; i<b.length(); i++) {
if (a==(b.substr(0, i)+b.substr(i+1))) {
return 1;
}
}
*/
}
return 0;
}

int  main()
{
vector<string> v;
string str;
while(cin>>str && str!="#")
v.push_back(str);
while(cin>>str && str!="#") {
bool sam=false;
vector<string> sim;
for (vector<string>::iterator it=v.begin(); it!=v.end(); it++) {
int t=issimilar(str, *it);
if (t==2) {
sam = true;
break;
}
else if (t==1) {
sim.push_back(*it);
}
}
if (sam == true) {
cout << str << " is correct" << endl;
}
else {
cout << str << ":";
for(int i=0; i<sim.size(); i++)
cout << " " << sim.at(i);
cout << endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: