如何测试字符串是否只有效地包含一个差异?

时间:2016-06-06 14:01:30

标签: java string

我在技术面试时被问到这个问题。问题是:给定一个目标和一个字符串数组,返回一个数组,其中包含与目标只有一个差异的所有字符串。

例如,如果目标是cat,catt,caT,caa,ca,at< - 只是一个区别。相反,cat,cattt,dog,flower,c< - 不是一个区别,不应该返回。

oneDiff(String target,String [] a)...

我的方法是:

  ans = []
  for all element e in the array
      count -> 0
      if absoulte(e's length - target length) > 1 
          continue
      endif
      for all character c in e
         scan through, increment count if difference is found. 
      endfor
      if (count == 1) 
         continue
      else 
         add e to ans
  endfor
  return ans

但面试官并不满意上述内容。任何人都有任何有效/聪明的想法?

谢谢

1 个答案:

答案 0 :(得分:4)

As mentioned by zubergu Levenshtein distance will solve your problem. You can find Levenshtein distance in java here.

Edit: Since you tagged it as <pre> you can run the following java code:

java

If you run the code you will see the following output:

public class Levenshtein {

    public static int distance(String a, String b) {
        a = a.toLowerCase();
        b = b.toLowerCase();
        // i == 0
        int [] costs = new int [b.length() + 1];
        for (int j = 0; j < costs.length; j++)
            costs[j] = j;
        for (int i = 1; i <= a.length(); i++) {
            // j == 0; nw = lev(i - 1, j)
            costs[0] = i;
            int nw = i - 1;
            for (int j = 1; j <= b.length(); j++) {
                int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
                nw = costs[j];
                costs[j] = cj;
            }
        }
        return costs[b.length()];
    }

    public static void main(String [] args) {
        String comparison = "cat";
        String [] data = { "cattt", "catt", "caT", "caa", "ca", "at" };
        for (int i = 0; i < data.length; i++)
            System.out.println("distance(" + comparison + ", " + data[i] + ") = " + distance(comparison, data[i]));
    }
}

If the distance(cat, cattt) = 2 distance(cat, catt) = 1 distance(cat, caT) = 0 distance(cat, caa) = 1 distance(cat, ca) = 1 distance(cat, at) = 1 is 0 or 1 then its acceptable.

相关问题