[LeetCode] Index Pairs of a String

1065. Index Pairs of a String

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<vector<int>> indexPairs(string text, vector<string>& words) {
vector<vector<int>> res;
for(auto w : words) {
if(w.length() > text.length()) continue;
for(int i = 0; i < text.length() - w.length() + 1; i++) {
if(text.substr(i,w.length()) == w) res.push_back({i,i+(int)w.length() - 1});
}
}
sort(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/01/PS/LeetCode/index-pairs-of-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.