My code:
public class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int i1 = -1;
int i2 = -1;
int ret = Integer.MAX_VALUE;
if (word1.equals(word2)) {
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
if (i2 < i1) {
i2 = i;
}
else {
i1 = i;
}
}
if (i1 != -1 && i2 != -1) {
ret = Math.min(ret, Math.abs(i1 - i2));
}
}
}
else {
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
i1 = i;
}
else if (words[i].equals(word2)) {
i2 = i;
}
if (i1 != -1 && i2 != -1) {
ret = Math.min(ret, Math.abs(i1 - i2));
}
}
}
return ret;
}
}
差不多的思路,可能代码写得丑了一点。
有个傻逼一直在说话,吵得我不能思考。。。
出去吃饭了。
Anyway, Good luck ,Richardo! — 09/05/2016