LeetCode 1065: Index Pairs of a String Solution
Master LeetCode problem 1065 (Index Pairs of a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
Given a string text and an array of strings words, we need to find all starting indices of words in the text string.
To solve this problem, we can iterate through the text string and check if each word in the words array matches the substring starting from the current index in the text string. If there is a match, we record the starting index and the ending index of the matched word.
Solution Code
class Solution {
public int[][] indexPairs(String text, String[] words) {
List<int[]> result = new ArrayList<>();
for (String word : words) {
int wordLen = word.length();
for (int i = 0; i <= text.length() - wordLen; i++) {
if (text.substring(i, i + wordLen).equals(word)) {
result.add(new int[] {i, i + wordLen - 1});
}
}
}
Collections.sort(result, (a, b) -> a[0] - b[0] != 0 ? a[0] - b[0] : a[1] - b[1]);
return result.toArray(new int[result.size()][]);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1065 (Index Pairs of a String)?
This page provides optimized solutions for LeetCode problem 1065 (Index Pairs of a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1065 (Index Pairs of a String)?
The time complexity for LeetCode 1065 (Index Pairs of a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1065 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1065 in Java, C++, or Python.