【发布时间】:2013-08-28 15:03:19
【问题描述】:
这是来自在线编码挑战之一的问题(已完成)。
我只需要一些关于如何处理的逻辑。
问题陈述:
我们有两个字符串 A 和 B 具有相同的超级字符集。我们需要改变这些字符串以获得两个相等的字符串。在每一步中,我们都可以执行以下操作之一:
1. swap two consecutive characters of a string
2. swap the first and the last characters of a string
可以对任一字符串执行移动。
为了获得两个相等的字符串,我们需要的最小步数是多少?
输入格式和约束:
输入的第一行和第二行包含两个字符串 A 和 B。保证它们的字符相等的超集。
1 <= length(A) = length(B) <= 2000
All the input characters are between 'a' and 'z'
输出格式:
将最小移动次数打印到输出的唯一行
Sample input:
aab
baa
Sample output:
1
说明:
交换字符串 aab 的第一个和最后一个字符以将其转换为 baa。这两个字符串现在相等了。
编辑:这是我的第一次尝试,但输出错误。有人可以指导我的方法有什么问题吗?
int minStringMoves(char* a, char* b) {
int length, pos, i, j, moves=0;
char *ptr;
length = strlen(a);
for(i=0;i<length;i++) {
// Find the first occurrence of b[i] in a
ptr = strchr(a,b[i]);
pos = ptr - a;
// If its the last element, swap with the first
if(i==0 && pos == length-1) {
swap(&a[0], &a[length-1]);
moves++;
}
// Else swap from current index till pos
else {
for(j=pos;j>i;j--) {
swap(&a[j],&a[j-1]);
moves++;
}
}
// If equal, break
if(strcmp(a,b) == 0)
break;
}
return moves;
}
【问题讨论】:
-
“这是来自...的问题” - 如果可能,链接总是有帮助的。
-
你对这个问题有什么想法?你试过什么了?您是否考虑过一些贪婪或动态编程方法?
-
可能是找到Levenshtein distance问题的特定版本。
-
通常,那些编码挑战网站会在挑战完成后发布答案。你在那里检查过吗?
-
@jambono 如果你读到他不是在寻求解决方案的问题,他是在寻求方法方面的帮助。