Shortest Word Distance I/II/III

要点:系列题最重要的是记清题,重点是题目本身的变化和解法之间的关联。

I https://repl.it/CqPf

  • 这题的一般规律从左到右的某个word提供了boundary为之后的word做比较用:所以遇到两个word中的一个,一是和另一个word比较,二是更新本word的boundary。
  • 和Closest Binary Search Tree Value很像,都是boundary限定

III https://repl.it/CqSA

  • I里面两个word不同,遇到任意一个和另一个是互斥的。所以III扩展为可能相同的情况,而word1==word2意义就变了:变成了两个word在不同位置的距离,如果还按1的方法,永远不能比较另一个word。
  • 简单的方法就是在处理第一个word的时候多检查word1word2,这时候和idx1本身算距离, 如果word1word2,就不会落到elif的branch

II https://repl.it/CqPa

  • 用map记录index,题目就转化成了类似merge的算法了。
# 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. # Hide Company Tags LinkedIn
# Hide Tags Array
# Hide Similar Problems (M) Shortest Word Distance II (M) Shortest Word Distance III class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
p1, p2 = -1, -1
shortest = len(words)
for i in xrange(len(words)):
if words[i]==word1:
if p2!=-1 and shortest > i-p2:
shortest = i-p2
p1 = i
elif words[i]==word2:
if p1!=-1 and shortest > i-p1:
shortest = i-p1
p2 = i return shortest
# This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

# 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.

# For example,
# Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. # Given word1 = “makes”, word2 = “coding”, return 1.
# Given word1 = "makes", word2 = "makes", return 3. # Note:
# You may assume word1 and word2 are both in the list. # Hide Company Tags LinkedIn
# Hide Tags Array
# Hide Similar Problems (E) Shortest Word Distance (M) Shortest Word Distance II class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
p1, p2 = -1, -1
shortest = len(words)
for i in xrange(len(words)):
if words[i]==word1:
if word1==word2 and p1!=-1:
shortest = min(shortest, i-p1)
elif p2!=-1:
shortest = min(shortest, i-p2)
p1 = i
elif words[i]==word2:
if p1!=-1:
shortest = min(shortest, i-p1)
p2 = i
return shortest
# This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?

# Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and 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. # Hide Company Tags LinkedIn
# Hide Tags Hash Table Design
# Hide Similar Problems (E) Merge Two Sorted Lists (E) Shortest Word Distance (M) Shortest Word Distance III from collections import defaultdict
class WordDistance(object):
def __init__(self, words):
"""
initialize your data structure here.
:type words: List[str]
"""
self.wordpos = defaultdict(list)
[self.wordpos[words[i]].append(i) for i in xrange(len(words))] def shortest(self, word1, word2):
"""
Adds a word into the data structure.
:type word1: str
:type word2: str
:rtype: int
"""
wl1 = self.wordpos[word1]
wl2 = self.wordpos[word2] i,j = 0,0
shortest = sys.maxint
while i<len(wl1) and j<len(wl2):
shortest = min(shortest, abs(wl1[i]-wl2[j]))
if wl1[i]<wl2[j]:
i+=1
else:
j+=1
return shortest # Your WordDistance object will be instantiated and called as such:
# wordDistance = WordDistance(words)
# wordDistance.shortest("word1", "word2")
# wordDistance.shortest("anotherWord1", "anotherWord2")

边工作边刷题:70天一遍leetcode: day 75-1的更多相关文章

  1. 边工作边刷题:70天一遍leetcode: day 75

    Group Shifted Strings 要点:开始就想到了string之间前后字符diff要相同. 思维混乱的地方:和某个string的diff之间是没有关系的.所以和单个string是否在那个点 ...

  2. 边工作边刷题:70天一遍leetcode: day 89

    Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...

  3. 边工作边刷题:70天一遍leetcode: day 77

    Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...

  4. 边工作边刷题:70天一遍leetcode: day 78

    Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...

  5. 边工作边刷题:70天一遍leetcode: day 85-3

    Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...

  6. 边工作边刷题:70天一遍leetcode: day 101

    dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...

  7. 边工作边刷题:70天一遍leetcode: day 1

    (今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...

  8. 边工作边刷题:70天一遍leetcode: day 70

    Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...

  9. 边工作边刷题:70天一遍leetcode: day 71-3

    Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...

  10. 边工作边刷题:70天一遍leetcode: day 71-2

    One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...

随机推荐

  1. HDU 2256 Problem of Precision 数论矩阵快速幂

    题目要求求出(√2+√3)2n的整数部分再mod 1024. (√2+√3)2n=(5+2√6)n 如果直接计算,用double存值,当n很大的时候,精度损失会变大,无法得到想要的结果. 我们发现(5 ...

  2. 关于我的OI生涯(AFO){NOIP2016 后}

    这篇我就随意写啦~不用统一的“题解”形式.♪(^∀^●)ノ 也分好几次慢慢更吧~ 对于NOIP2016的总结,我本想善始善终back回,但是心情不足以支撑我,那就只能有始有终了......下面进入我的 ...

  3. ArrayList集合

    //在使用ArrayList时别忘了引用命名空间 using System.Collections;//首先得导入命名空间 //01.添加方法 add方法 //告诉内存,我要存储内容 ArrayLis ...

  4. 用EF6更新数据库时出现外键错误解决方式

    在“Package Manager Console”中执行update-database命令,出现异常信息: Introducing FOREIGN KEY constraint 'FK_dbo.Pr ...

  5. [Tool] 使用StyleCop验证命名规则

    [Tool] 使用StyleCop验证命名规则 前言 微软的MSDN上,有提供了一份微软的命名方针,指引开发人员去建立风格一致的程序代码. http://msdn.microsoft.com/zh-t ...

  6. Xml序列化、反序列化帮助类

    之前从网络上找了一个Xml处理帮助类,并整理了一下,这个帮助类针对Object类型进行序列化和反序列化,而不需要提前定义Xml的结构,把它放在这儿供以后使用 /// <summary> / ...

  7. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q32-Q34)

    Question 32You create a custom Web Part.You need to ensure that a custom property is visible in Edit ...

  8. 一个线程加一运算,一个线程做减一运算,多个线程同时交替运行--synchronized

    使用synchronized package com.pb.thread.demo5; /**使用synchronized * 一个线程加一运算,一个线程做减法运算,多个线程同时交替运行 * * @a ...

  9. CSS 指定选择器(十一)

    一.指定选择器 有时个会希望控制某个元素在一定范围内的对象样式,这时就可以把元素与Class或者Id选择器结合起来使用 <!DOCTYPE html PUBLIC "-//W3C//D ...

  10. Android UI之下拉刷新上拉刷新实现

    在实际开发中我们经常要用到上拉刷新和下拉刷新,因此今天我写了一个上拉和下拉刷新的demo,有一个自定义的下拉刷新控件 只需要在布局文件中直接引用就可以使用,非常方便,非常使用,以下是源代码: 自定义的 ...