字符串算法作业/面试就像问题

时间:2011-04-03 12:56:37

标签: algorithm string pseudocode

让我们说我们必须使用字符串A和B.任务是在字符串B中插入任何需要的字母,以便最终得到字符串A.

例如:

A - This is just a simple test 
B - is t a sim te

所以,如果我们像这样看字符串A:

--is -- ---t a sim--- te--

或:

---- is ---t a sim--- te--
很明显,我们可以从字符串B构建字符串A,输出应该是上面写的格式(两个答案都是正确的)。

你能想到一个能在合理的时间内解决这个问题的算法吗?提出强力解决方案非常容易,但我需要比这更复杂的东西。

5 个答案:

答案 0 :(得分:3)

您可以将Levenshtein distance algorithm作为基础并将其扩展为还记住添加/删除/替换的字符。那将是线性时间。

答案 1 :(得分:2)

您可以在A中找到B中第一次出现的字符,只需在A中找到最后一个索引后开始查找事件,例如在您的情况下:

A - This is just a simple test 
B - is t a sim te

i: 3rd place in A,
s: 4th place in A,
' ': 5th place in A,
t: 12th place in A, (because last index was 4)
' ': ...
a: ....

那是O(|A|+|B|),因为|A| > |B|O(|A|)

找到索引后,很容易将B转换为A,只需在B的两个索引之间添加A的字符。

编辑:此外,如果此算法不匹配,则工作正常(B中的某些字符不在A中,来自最后一个索引)。

答案 2 :(得分:0)

我认为你可以通过一个很好的reg表达来确定它是否可行。因为B中建议的任何一个或多个字符可能有也可能没有。

答案 3 :(得分:0)

我认为你可以在线性时间和空间中做到这一点(伪代码,完全未经测试):

String f( String a, String b ) {
  String result;

  // Iterate over 'a' and 'b' in parallel. If both have the same
  // character, add it to the result. Otherwise, if 'a' has a space add a space to the result, otherwise add a dash.
  int idxB = 0;
  for (int idxA = 0; idxA < a.length(); ++idxA ) {
    if (a[idxA] == b[idxB]) {
      result.append(a[idxA]);
      ++idxB;
    } else if (a[idxA] == ' ') {
      result.append(' ');
    } else {
      result.append('-');
    }
  }

  // Tack on dashes to the result until it's as long as 'a'.
  while (result.length() < a.length()) {
    result.append('-');
  }

  return result;
}

答案 4 :(得分:0)

我实际上认为蛮力将是最快的,但你必须改变字符串A才能在一次通过中进行紧固...只需迭代A将每个字母更改为“ - ”与您正在寻找的字母不匹配除非它是一种空间类型的交易...这将是恒定的时间,不需要额外的存储...基本上你的时间将是N.当然你必须处理来自“B”的令牌,所以一旦你找到“我“你需要确保下一个字母是”s“,这样你才能找到”是“,但仍然应该很快,如果下一个字母不是s那就不要回到我的位置...应该指向正确的方向而不给你解决你的作业...