243:最短单词距离

This commit is contained in:
轩辕龙儿 2022-04-11 11:28:22 +08:00
parent d3bf1deb4a
commit 76aff63c46
2 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,65 @@
//给定一个字符串数组 wordDict 和两个已经存在于该数组中的不同的字符串 word1 word2 返回列表中这两个单词之间的最短距离
//
//
//
// 示例 1:
//
//
//输入: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 =
//"coding", word2 = "practice"
//输出: 3
//
//
// 示例 2:
//
//
//输入: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 =
//"makes", word2 = "coding"
//输出: 1
//
//
//
// 提示:
//
//
// 1 <= wordsDict.length <= 3 * 10
// 1 <= wordsDict[i].length <= 10
// wordsDict[i] 由小写英文字母组成
// word1 word2 wordsDict
// word1 != word2
//
// Related Topics 数组 字符串 👍 90 👎 0
package leetcode.editor.cn;
//243:最短单词距离
public class ShortestWordDistance {
public static void main(String[] args) {
Solution solution = new ShortestWordDistance().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int shortestDistance(String[] wordsDict, String word1, String word2) {
int[] arrs = new int[]{-1, -1};
int length = wordsDict.length;
for (int i = 0; i < wordsDict.length; i++) {
if (wordsDict[i].equals(word1)) {
arrs[0] = i;
if(arrs[1]>-1){
length = Math.min(length,arrs[0]-arrs[1]);
}
}else if (wordsDict[i].equals(word2)) {
arrs[1] = i;
if(arrs[0]>-1){
length = Math.min(length,arrs[1]-arrs[0]);
}
}
}
return length;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,29 @@
<p>给定一个字符串数组&nbsp;<code>wordDict</code>&nbsp;和两个已经存在于该数组中的不同的字符串&nbsp;<code>word1</code><code>word2</code> 。返回列表中这两个单词之间的最短距离。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
<strong>输出:</strong> 3
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre>
<strong>输入:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
<strong>输出:</strong> 1</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong><meta charset="UTF-8" /></p>
<ul>
<li><code>1 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li>
<li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li>
<li><code>wordsDict[i]</code>&nbsp;由小写英文字母组成</li>
<li><code>word1</code>&nbsp;&nbsp;<code>word2</code>&nbsp;&nbsp;<code>wordsDict</code></li>
<li><code>word1 != word2</code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>字符串</li></div></div><br><div><li>👍 90</li><li>👎 0</li></div>