Python 中的字符串索引对


假設我們有一個文字字串和一個單字陣列 (由一個字串清單組成),我們要找出所有索引對 [i, j],使得子字串 text[i]...text[j] 在單字清單之中。因此,如果字串為 “ababa” 而單字陣列為 [“aba”, “ab”],則輸出將為 [[0,1], [0,2], [2,3], [2,4]]。我們可以注意到的一點是,配對之間可能重疊,例如在 [0,2] 和 [2,4] 中都配對到了字串 “aba”。

為了解決這個問題,我們將執行下列步驟−

  • res := 一個空清單
  • 針對字串長度範圍內所有 i
    • 針對字串長度範圍內所有 i + 1 到 i 的 j
      • 如果子字串從索引 i 到 j 出現在單字清單中 −
        • 將 (i, j – 1) 加入結果陣列中
  • 傳回結果

範例(Python)

我們來看看以下實作方式,以更進一步了解這個概念 −

 動態展示

class Solution(object):
   def indexPairs(self, text, words):
      result = []
      for i in range(len(text)):
         for j in range(i+1,len(text)+1):
            if text[i:j] in words:
               result.append([i,j-1])
      return result
ob1 = Solution()
print(ob1.indexPairs("ababa",["aba","ab"]))

輸入

"ababa"
["aba","ab"]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

輸出

[[0,1],[0,2],[2,3],[2,4]]

更新於: 28-4-2020

805 次瀏覽

开启您的职业生涯

通过完成课程获得认证

立即开始
广告