- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Index Pairs of a String in Python
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
- if substring of string from index i to j in words −
- for j in range i + 1 to length of string + 1
- return result
Example(Python)
Let us see the following implementation to get a better understanding −
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]]
Advertisements