- 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤&𝗔 𝗣𝗮𝗰𝗸𝗮𝗴𝗲 𝗳𝗼𝗿 𝗧𝗲𝘀𝘁 𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗼𝗻 & 𝗦𝗗𝗘𝗧: 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