lintcode 924. 单词最短距离

给出一个单词列表和两个单词单词1,单词2,返回列表中这两个单词之间的最短距离。

样例
样例 1:

输入:["practice", "makes", "perfect", "coding", "makes"],"coding","practice"
输出:3
解释:index("coding") - index("practice") = 3
样例 2:

输入:["practice", "makes", "perfect", "coding", "makes"],"makes","coding"
输出:1
解释:index("makes") - index("coding") = 1
注意事项
您可以假定单词1不等于单词2,而单词1和单词2在列表中都存在。
class Solution {
public:
    /**
     * @param words: a list of words
     * @param word1: a string
     * @param word2: a string
     * @return: the shortest distance between word1 and word2 in the list
     */
    int shortestDistance(vector<string> &words, string &word1, string &word2) {
        // Write your code here
        int index1=-1;
        int index2=-1;
        int mins=words.size();
        for (int i = 0; i < words.size(); i++) {
            /* code */
            if(words[i]==word1) index1=i;
            else if(words[i]==word2) index2=i;
            else continue;
            if(index1>=0&&index2>=0) mins=min(mins,abs(index2-index1));
        }
        return mins;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值