277. 单词间距
给出一系列单词
words
,以及两个不同的单词
wordA
和
wordB
,请找出最近的两个
wordA
和
wordB
的间距。
如果
words
中不存在
wordA
或
wordB
,那么返回
-1
−
1
。
样例
输入:
["hello","world","say","hello"]
"hello"
"world"
输出:
1
说明
样例中,第一个 "hello" 和第一个 "world" 的间距为
1
1
,
但第一个 "world" 和第二个 "hello" 的间距为
2
2
, 所以最后的答案应该是
1
1
.
注意事项
words
中有
t
t
个单词,每个单词的长度为
k
k
,
1 \le t \le 10^4
1
≤
t
≤
1
0
4
,
1 \le k \le 20
1
≤
k
≤
2
0
。
wordA
和
wordB
的长度分别为
n, m
n
,
m
,
1 \le n, m \le 20
1
≤
n
,
m
≤
2
0
。
单词只包含大写或小写英文字符。
public class Solution {
/**
* @param words: the words given.
* @param wordA: the first word you need to find.
* @param wordB: the second word you need to find.
* @return: return the spacing of the closest wordA and wordB.
*/
public int wordSpacing(List<String> words, String wordA, String wordB) {
// write your code here.
int sum = Integer.MAX_VALUE;
int start;
int end = 0;
boolean aStart = false, bStart = false;
for (int i = 0; i < words.size(); i++) {
if (wordA.equals(words.get(i))) {
start = end;
end = i;
if (end != 0 && bStart) {
sum = Math.min(sum, end - start);
}
aStart = true;
bStart = false;
} else if (wordB.equals(words.get(i))) {
start = end;
end = i;
if (end != 0 && aStart) {
sum = Math.min(sum, end - start);
}
bStart = true;
aStart=false;
}
}
return sum == Integer.MAX_VALUE ? -1 : sum;
}
}