881355. Case Insensitive Search
Case Insensitive Search
Summary
The case insensitive search problem involves finding a given pattern in a string while ignoring the case (i.e., treating uppercase and lowercase letters as the same). This problem is related to strings and pattern searching.
Detailed Explanation
To solve this problem, we can use a simple approach by converting both the target string and the search pattern into either all uppercase or all lowercase before performing the search. This way, we can ensure that the comparison is case-insensitive.
Here's a step-by-step breakdown of the solution:
- Convert the target string and the search pattern into either all uppercase or all lowercase.
- Compare each character in the target string with the corresponding character in the search pattern (after conversion).
- If the characters match, return the starting index of the pattern in the target string.
Here's a sample ASCII art diagram to illustrate the process:
Target String: Hello World
Search Pattern: hello
1. Convert both strings to lowercase:
Target String: hello world
Search Pattern: hello
2. Compare characters:
'h' (target) == 'h' (pattern)
'e' (target) == 'e' (pattern)
...
3. Return the starting index of the pattern in the target string: 0
Time complexity for this solution is O(n), where n is the length of the target string, as we need to iterate through each character in the target string once. Space complexity is O(1), as we only require a constant amount of space to store the converted strings.
Optimized Solutions
Java
public int caseInsensitiveSearch(String target, String pattern) {
int targetLength = target.length();
int patternLength = pattern.length();
for (int i = 0; i <= targetLength - patternLength; i++) {
boolean match = true;
for (int j = 0; j < patternLength; j++) {
if (Character.toLowerCase(target.charAt(i + j)) != Character.toLowerCase(pattern.charAt(j))) {
match = false;
break;
}
}
if (match) return i;
}
return -1;
}