iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
0
Software Development

刷刷題 or Alan Becker's game 製作 is a question 系列 第 28

(Hard) 30. Substring with Concatenation of All Words

  • 分享至 

  • xImage
  •  

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 : 時間/空間 複雜度 有很大進步空間


上一篇
(Medium) 29. Divide Two Integers #水
下一篇
(Medium) 31. Next Permutation
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言