有两个字符串s 和 u, 问最少的步数从s转换倒u。
转换的方法,
从s任意取一个substring,然后可以执行以下三种操作
Insert one letter to any end of the string.
Delete one letter from any end of the string.
Change one letter into any other one.
参考:
转换的方法,
从s任意取一个substring,然后可以执行以下三种操作
Insert one letter to any end of the string.
Delete one letter from any end of the string.
Change one letter into any other one.
也就是说从s找一个substring,使得以上三种操作的步数最小,转换倒u。
发信人: chump (chump), 信区: JobHunting
标 题: Re: 刚做了一道题挺有意思
发信站: BBS 未名空间站 (Thu Mar 1 19:25:22 2012, 美东)
我觉得就是字符串的匹配问题吧。 用u匹配s的每个等长字串,看看有多少个字符不同
。考虑到u的开始和结束的特殊情况,可以在u的前后加上足够的pad.
#include <string>
#include <iostream>
using namespace std;
const char PAD = '$';
int match(string p, string q, size_t len)
{
int count = 0;
for(size_t i = 0; i < len; i++){
if (p.at(i) != q.at(i)){
count++;
}
}
return count;
}
size_t edit (string from, string to, string& sub)
{
string pad;
pad.append( to.length()-1, PAD);
from = pad+from+pad;
int count = INT_MAX;
for (size_t i = 0; i <= from.length() - to.length(); i++ ){
string str = from.substr(i, to.length());
int cur = match(str, to, to.length());
if (cur < count){
count = cur;
sub = str;
}
}
while(sub.at(sub.length()-1) == PAD ){
sub = sub.substr(0, sub.length()-1);
}
while(sub.at(0) == PAD ){
sub = sub.substr(1, sub.length()-1);
}
return count;
}
int main() {
string a ="aabgccc";
string b = "bec";
string sub;
cout << "a=" << a <<"; b=" << b << "; edit cost =" << edit(a, b, sub) <<
"; substring =" << sub << endl;
return 0;
}
参考:
http://codercareer.blogspot.com/2011/12/no-25-edit-distance.html
本文探讨了将一个字符串转换为另一个字符串所需的最小编辑步骤,包括插入、删除和替换操作。通过实例代码展示了如何实现这一过程,并提供了相关链接以深入学习。
1263

被折叠的 条评论
为什么被折叠?



