30. Substring with Concatenation of All Words
2016-08-02 16:08
197 查看
题目
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.For example, given:
s: “barfoothefoobarman”
words: [“foo”, “bar”]
You should return the indices: [0,9].
(order does not matter).
分析
解决该问题的关键是理解清楚要求。给定一个目标字符串s,一个单词集合words。
要求使得words集合中所有元素连续出现在s中的首位置组成的集合(元素顺序不考虑)。
正如所给实例,目标字符串s: “barfoothefoobarman”
对比单词集合words: [“foo”, “bar”]
我们发现,在pos=0 ~ 5时“barfoo”恰好匹配,则0加入结果result;
在pos=9 ~ 14时“foobar”恰好匹配,则9加入结果result;
在理清楚题意后,便可入手程序实现。
class Solution(object): ##判断是否有words中的单组组成 def isEqual(self, s, words, n): sList = [] i = 0 // 将字符串按照 words中每个单词的长度截取成数组 while(i<len(s)): sList.append(s[i:i+n]) i = i + n sList.sort() words.sort() if sList== words: return True else: return False def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ if len(words)<=0: return n = len(words[0]) lenWord = n *len(words) result = [] i = 0 #注意while 的跳出条件 只需要循环 len(s)-lenWord次就够了 while(i<=len(s)-lenWord): sCurrent = s[i:i+n] if sCurrent in words: #取出长度等于words中所有单词组成字符串的长度的S的字串 sSub = s[i:lenWord+i] if self.isEqual(sSub, words,n): result.append(i) #每次i增1 i += 1 return result
相关文章推荐
- LeetCode 30. Substring with Concatenation of All Words
- leetcode 30: Substring with Concatenation of All Words
- leetCode 30.Substring with Concatenation of All Words (words中所有子串相连) 解题思路和方法
- 30. Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- [Leetcode]30. Substring with Concatenation of All Words @python
- leetcode 30. Substring with Concatenation of All Words
- LeetCode 30 Substring with Concatenation of All Words
- LeetCode 30 Substring with Concatenation of All Words
- [LeetCode]30. Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- leetcode[30]Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- [LeetCode] 30. Substring with Concatenation of All Words ☆☆☆
- 30 Substring with Concatenation of All Words
- LeetCode 30 Substring with Concatenation of All Words 解法为Hashmap
- LeetCode----30. Substring with Concatenation of All Words(串联所有的words)
- leetcode (30) Substring with Concatenation of All Words
- LeetCode 30. Substring with Concatenation of All Words