889415. Remove all occurrences of a character in a string
Remove all occurrences of a character in a string
Summary
The problem is to remove all occurrences of a specific character from a given string. This involves iterating over the input string, identifying and removing instances of the target character.
Detailed Explanation
To solve this problem, we can iterate through the input string using a for loop or equivalent. For each character in the string, we check if it matches our target character. If it does, we remove it from the string. We can use various methods to achieve this, such as replacing the target character with an empty string, or manually manipulating the characters.
Here's a step-by-step breakdown of the solution:
- Initialize an empty string
resultto store the modified input string. - Iterate through each character
charin the input string. - Check if
charmatches our target character (e.g., using the equality operator). - If it does, append the remaining characters up to the current index to
result. - Remove the matched character from the original string by skipping it during iteration.
- Repeat steps 2-5 until all characters have been processed.
- Return the modified
resultstring.
Time complexity: O(n), where n is the length of the input string, as we iterate through each character once. Space complexity: O(1), since we only use a constant amount of space to store our result and temporary variables.
Optimized Solutions
Java
public String removeCharacter(String str, char c) {
StringBuilder result = new StringBuilder();
for (char ch : str.toCharArray()) {
if (ch != c) {
result.append(ch);
}
}
return result.toString();
}