Given a string text
and an array of strings words
, return an array of all index pairs [i, j]
so that the substring text[i...j]
is in words
.
Return the pairs [i, j]
in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second coordinate).
Example 1:
Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] Output: [[3,7],[9,13],[10,17]]
Example 2:
Input: text = "ababa", words = ["aba","ab"] Output: [[0,1],[0,2],[2,3],[2,4]] Explanation: Notice that matches can overlap, see "aba" is found in [0,2] and [2,4].
Constraints:
1 <= text.length <= 100
1 <= words.length <= 20
1 <= words[i].length <= 50
text
andwords[i]
consist of lowercase English letters.- All the strings of
words
are unique.
Companies:
Amazon
Related Topics:
Array, String, Trie, Sorting
// OJ: https://leetcode.com/problems/index-pairs-of-a-string/
// Author: github.com/lzl124631x
// Time: O((T-W) * (T+W) * N) where `T` is the length of `text`, `W` is the maximum length of word in `words`, and `N` is the length of `words`.
// Space: O(1) extra space
class Solution {
public:
vector<vector<int>> indexPairs(string text, vector<string>& A) {
vector<vector<int>> ans;
for (auto &s : A) {
int i = text.find(s);
while (i != string::npos) {
ans.push_back({ i, i + (int)s.size() - 1 });
i = text.find(s, i + 1);
}
}
sort(begin(ans), end(ans));
return ans;
}
};