topic
数组中两个字符串的最小距离
java code
package com.lizhouwei.chapter5;
/**
* @Description: 数组中两个字符串的最小距离
* @Author: lizhouwei
* @CreateDate: 2018/4/25 20:30
* @Modify by:
* @ModifyDate:
*/
public class Chapter5_12 {
public int minDistance(String[] strings, String str1, String str2) {
if (str1 == null || str2 == null) {
return -1;
}
if (str1.equals(str2)) {
return 0;
}
int last1 = -1;
int last2 = -1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < strings.length; i++) {
if (str1.equals(strings[i])) {
last1 = i;
min = Math.min(min, last2 == -1 ? min : last1 - last2);
}
if (str2.equals(strings[i])) {
last2 = i;
min = Math.min(min, last1 == -1 ? min : last2 - last1);
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
//测试
public static void main(String[] args) {
Chapter5_12 chapter = new Chapter5_12();
String[] str = {"1", "3", "3", "3", "2", "3", "1"};
int result = chapter.minDistance(str, "1", "2");
System.out.println("{\"1\",\"3\",\"3\",\"3\",\"2\",\"3\",\"1\"}中:");
System.out.println("1和2的最小距离:" + result);
}
}
result
![](https://images2018.cnblogs.com/blog/1369004/201804/1369004-20180425220630754-1326300485.png)