Leetcode - Shortest Word Distance II
Leetcode - Create Target Array in the Given Order

Leetcode - Shortest Word Distance III

violet posted @ Apr 02, 2020 04:56:10 AM in 算法 with tags Algorithm Golang TwoPointers array , 220 阅读

https://leetcode.com/problems/shortest-word-distance-iii/

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

 

Somehow this is a series of problems. The pattern is

p1 = 0
p2 = p1 + 1
for p2 < len(arr) {
    for p1 < len(arr) && p1condition {
        p1++
    }
    p2 = p1+1
    for p2 < len(arr) && p2condition {
        p2++
    }
    if p2 >= len(arr) {
        break  
    }
    do something

    update p1
}
func shortestWordDistance(words []string, word1 string, word2 string) int {
    left := 0
    right := left + 1
    result := math.MaxInt32
    for right < len(words) {
        for left < len(words) && words[left] != word1 && words[left] != word2 {
            left++
        }
        first := words[left]
        var second string
        if first == word1 {
            second = word2
        } else {
            second = word1
        }
        right = left+1
        for right < len(words) && words[right] != second {
            right++
        }
        if right >= len(words) {
            break
        }
        result = min(result, right - left)
        left++
    }
    return result
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}
Plus Two New Questio 说:
Feb 12, 2023 04:51:54 PM

Plus Two New Question Paper 2024 and Board Model Paper 2024 The Board of Secondary Education has declared the Board Question Paper 2024 of 2nd Year Intermediate Class. Plus Two New Question Paper 2024 If you are also one of the enrolling students of this board and waiting for 2nd Year Intermediate Model Paper 2024. Important Question Paper 2024 then take the patient for some time and check the final passing list through the link which is mentioned at the bottom of the page.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter