Index Pairs of a String in Python

PythonServer Side ProgrammingProgramming

Suppose we have a text string and words (a list of strings), we have to find all index pairs [i, j] such that the substring text[i]...text[j] is in the list of words. So if the string is like “ababa” and words array is like [“aba”, “ab”], then the output will be [[0,1], [0,2], [2,3], [2,4]]. One thing we can notice, that the matches can overlap, the “aba” is matched in [0,2] and [2,4].

To solve this, we will follow these steps −

  • res := an empty list
  • for i in range 0 to a length of string
    • for j in range i + 1 to length of string + 1
      • if substring of string from index i to j in words −
        • add (i, j – 1) into the result array
  • return result

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

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"]))

Input

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

Output

[[0,1],[0,2],[2,3],[2,4]]
raja
Published on 27-Feb-2020 06:57:40
Advertisements