713193. Geeks And The String
Geeks And The String
Summary
Given a string str and an integer n, find all substrings of length n in str that contain at least one "geek" and exactly one "and". Return these substrings as a list.
This problem involves using a stack data structure to efficiently find the desired substrings.
Detailed Explanation
To solve this problem, we can use a stack-based approach. We iterate through the string str, keeping track of the last n characters in a stack. When we encounter an "and", we pop elements from the stack until we either run out of elements or find a substring that contains at least one "geek". If we find such a substring, we add it to our result list.
Here's a step-by-step breakdown:
- Initialize an empty stack
sand an empty listresult. - Iterate through
str, character by character. - For each character:
- If the character is "and", pop elements from
suntil we either run out of elements or find a substring that contains at least one "geek". - If the popped elements form a valid substring (i.e., it contains at least one "geek" and exactly one "and"), add it to
result.
- If the character is "and", pop elements from
- Return
result.
Time complexity: O(N), where N is the length of the input string. Space complexity: O(1), since we only use a constant amount of space to store the stack and result list.
Optimized Solutions
Java
import java.util.*;
public class GeeksAndTheString {
public static List<String> geeksAndTheString(String str, int n) {
List<String> result = new ArrayList<>();
Stack<Character> s = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == 'a' && s.size() >= n - 1) {
// Found a valid substring, add it to result
String temp = "";
while (!s.isEmpty()) {
temp = (char)s.pop() + temp;
}
result.add(temp);
} else if (c != 'a' && c != 'n' && c != 'd') {
s.push(c);
} else if (c == 'n') {
// Found an "and", pop elements until we find a "geek"
while (!s.isEmpty() && (char)s.peek() != 'g') {
s.pop();
}
if (!s.isEmpty()) {
s.pop(); // Remove the "g" from the stack
}
}
}
return result;
}
}