Removing Stars From a String with Java

🚀Day 24 of #75DaysofLeetCode LeetCode Problem Solved: Removing Stars From a String (2390) Today I solved the problem “Removing Stars From a String.” 🔹 Problem Statement: We are given a string containing characters and *. Each * removes the closest non-star character to its left, along with the * itself. The task is to return the final string after all stars are processed. 💡 Approach: The most efficient way to solve this is using a Stack-like approach. 1️⃣ Traverse the string from left to right. 2️⃣ If the character is not *, add it to the result (stack). 3️⃣ If the character is *, remove the last added character. 4️⃣ Continue until the string is processed. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 💻 Java Implementation: class Solution { public String removeStars(String s) { StringBuilder sb = new StringBuilder(); for(char c : s.toCharArray()) { if(c == '*') { sb.deleteCharAt(sb.length() - 1); } else { sb.append(c); } } return sb.toString(); } } ✨ Key Learning: Using a stack or StringBuilder helps efficiently simulate the removal of the closest character on the left. #LeetCode #Java #DataStructures #ProblemSolving #CodingPractice #100DaysOfCode

  • text

To view or add a comment, sign in

Explore content categories