- ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐ ๐ค&๐ ๐ฃ๐ฎ๐ฐ๐ธ๐ฎ๐ด๐ฒ ๐ณ๐ผ๐ฟ ๐ง๐ฒ๐๐ ๐๐๐๐ผ๐บ๐ฎ๐๐ถ๐ผ๐ป & ๐ฆ๐๐๐ง: https://topmate.io/sidharth_shukla/605319
Problem: Remove All Occurrences of a Given Character
Problem Statement:
Given a string s
and a character ch
, remove all occurrences of ch
from s
using the two-pointer approach.
Example 1:
Input: "apple", 'p'
Output: "ale"
Example 2:
Input: "banana", 'a'
Output: "bnn"
Java Solution (Two-Pointer Approach)
public class RemoveCharacter { public static String removeChar(String s, char ch) {
char[] chars = s.toCharArray();
int j = 0; // Pointer for placing valid characters
for (int i = 0; i < chars.length; i++) {
if (chars[i] != ch) {
chars[j] = chars[i];
j++; // Move valid character index forward
}
}
return new String(chars, 0, j);
}
public static void main(String[] args) {
System.out.println(removeChar("apple", 'p')); // Output: "ale"
System.out.println(removeChar("banana", 'a')); // Output: "bnn"
}
}
Explanation (Two-Pointer Approach)
-
Use Two Pointers:
i
iterates through the original string.j
keeps track of the next position for valid characters.
-
Skip the Character to Remove:
- If
s[i]
is not equal toch
, move it toj
position.
- If
-
Return New String Without the Removed Characters.
Time Complexity: O(n)
(single pass through the string)
Space Complexity: O(n)
(output string storage)
๐ฅ This is an easy and efficient way to remove a character from a string using two pointers! ๐
*** - ๐๐ฎ๐๐ฎ ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐ ๐ค&๐ ๐ฃ๐ฎ๐ฐ๐ธ๐ฎ๐ด๐ฒ: https://topmate.io/sidharth_shukla/1170024 - Learn Test Automation with 1:1 Guidance & Interview Preparation: https://lnkd.in/giCxnJJ7. HOLI Discount: Use Code ๐ฆ๐๐๐๐๐ฅ๐ง๐๐ญ๐ฌ to get 10% Discount (ONLY for first 10 enrollments): https://lnkd.in/giCxnJJ7 ****
No comments:
Post a Comment