277. 单词间距

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;
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时代我西

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值