Leetcode Everyday: 243. Shortest Word Distance
2016-05-11 23:36
323 查看
https://leetcode.com/problems/shortest-word-distance/
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
Given word1 =
return 3.
Given word1 =
return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
["practice", "makes", "perfect", "coding", "makes"].
Given word1 =
“coding”, word2 =
“practice”,
return 3.
Given word1 =
"makes", word2 =
"coding",
return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
public class Solution { public int shortestDistance(String[] words, String word1, String word2) { int i1 = -1; int i2 = -1; int dis = Integer.MAX_VALUE; for(int i = 0; i<words.length;i++){ String s = words[i]; if(s.equals(word1)){ i1 = i; if(i2!=-1 && i1-i2<dis) dis = i1-i2; } if(s.equals(word2)){ i2 = i; if(i1!=-1 && i2-i1<dis) dis = i2-i1; } } return dis; } }
相关文章推荐
- TextVersion_06_Android性能优化
- django中templates在settings的配置
- 个人开公司的流程及费用
- Java对象序列化ObjectOutputStream和ObjectInputStream示例
- Windows网络编程学习笔记(3) 编写一个TCP服务端
- Apache HttpServer启动出错处理
- TextVersion_05_OOM异常
- 管理 node 版本,选择 nvm 还是 n?
- Integrating C++ with QML
- 同步、异步、阻塞与非阻塞
- Integrating C++ with QML
- Linux基础知识
- TextVersion_04_TabLayout结合ViewPager
- ABP Zero源码
- UIView控件
- RMQ算法
- window窗口运行机制
- Redis之2-双端链表(adlist.c,adlist.h)
- win7 x64部署和串口调试虚拟驱动toaster
- ifconfig命令