Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func shortestWordDistance(_ words: [String], _ word1: String, _ word2: String) -> Int {
- if word1 == word2 {
- return findSame(word1, words)
- }
- var res = Int.max
- var p1 = -1
- var p2 = -1
- for (index, w) in words.enumerated() {
- if w == word1 {
- p1 = index
- if p2 != -1 { res = min(res, abs(p1 - p2))}
- }else if w == word2 {
- p2 = index
- if p1 != -1 { res = min(res, abs(p1 - p2))}
- }
- }
- return res
- }
- func findSame(_ word: String, _ arr:[String]) -> Int{
- var p = -1
- var res = Int.max
- for (index, w)in arr.enumerated(){
- if w == word{
- if p != -1 {
- res = min(res, abs(p - index))
- }
- p = index
- }
- }
- return res
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement