You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.
You can return the answer in any order.
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
Output: [6,9,12]
Constraints:
1 <= s.length <= 104
s consists of lower-case English letters.
1 <= words.length <= 5000
1 <= words[i].length <= 30
words[i] consists of lower-case English letters.
思路:
先计算每次shift: 单词长度 x 单词量
依每次 shift 可组出 所有可能
再由每个可能出发
把 words中 与存在每个可能的 token(与单一单词长度一样)的element 依序扣除
最後
如果 words 长度为 0 则可加进 答案
Code:
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
shift=len(words)*len(words[0])
wl=len(words[0])
#print(shift)
ansList = []
cnt = 0
while cnt < len(s):
if cnt+shift >len(s):
break
tmp = s[cnt:cnt+shift]
tmp2 = tmp
flag = 0
#print(tmp2)
'''
for i in words:
#if i not in tmp:
# flag = 1
if i in tmp:
#tmp.remove(i)
#print(i)
rmv=tmp.replace(i,"",1)
#print(rmv)
tmp = rmv
else:
flag = 1
break
'''
tw = words.copy()
#print("tw",tw)
j = 0
while j < len(tmp):
if tmp[j:j+wl] in tw:
try:
tw.remove(tmp[j:j+wl])
except:
#print("NoIN")
pass
j = j+wl
#print(">>>",len(tw))
if len(tw)==0:
ansList.append(cnt)
#if flag == 0:
# ansList.append(cnt)
#print(tmp)
cnt+=1
#print(ansList)
return ansList
Result:
先不要
Status : AC
But : 时间/空间 复杂度 有很大进步空间
<<: Day31 - 在 Windows 底下的 Ubuntu 18.04 执行 Ruby on Rails 的 RSpec Capybara 能显示 Chrome 浏览器跑 E2E 测试
>>: 30个实用网路行销工具(2020),从Google SEO、FB社群行销再到网站分析
「在未来,浏览器会变得越来越强,以後我们可以在浏览器做越来越多事。」 身为常与浏览器共舞的 Web...
1. 条件变数的Wait方法,做了什麽? Wait方法的用途,为等待通知。 先看一下Wait方法的程...
平常我们很少关注编译和链结的过程,因为开发环境都集成开发的环境,比如Visual Studio、Ec...
今天继续来说明class 相关的语法。今天提到的语法又会更抽象一点 extends 所谓继承就是我们...
Image optimzation 在 Next.js 10 版以後发布了 <Image /&...