889201. Search a Character in a String
Search a Character in a String
Slug: search-a-character-in-a-string Difficulty: Easy Id: 889201
Summary
This problem requires you to write an algorithm that searches for a specific character in a given string. The goal is to find the first occurrence of the target character in the string and return its index.
Detailed Explanation
To solve this problem, we can use a simple iterative approach. We iterate through each character in the string and check if it matches the target character. If we find a match, we return the current index as the result.
Here's the step-by-step breakdown of the solution:
- Initialize an index variable to 0.
- Iterate through each character
cin the input string. - For each character, check if it matches the target character using a conditional statement (e.g.,
if (c == targetCharacter)). - If the current character matches the target character, return the current index as the result.
- If we reach the end of the string without finding the target character, return -1 to indicate that the character was not found.
Here's an ASCII art diagram illustrating the algorithm:
+---------------+
| Input String |
+---------------+
|
v
+---------------+
| Iterate through |
| each character |
+---------------+
|
v
+---------------+
| Check if current |
| character matches|
| target character |
+---------------+
|
v
+---------------+
| Return index if |
| match found, -1 |
| otherwise |
+---------------+
Time complexity: O(n), where n is the length of the input string. Space complexity: O(1), as we only use a few extra variables to store the index and the target character.
Optimized Solutions
Java
public int searchCharacter(String s, char c) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
return i;
}
}
return -1;
}