|
| 1 | +/* |
| 2 | +Removing Stars From a String |
| 3 | +https://leetcode.com/problems/removing-stars-from-a-string/ |
| 4 | +
|
| 5 | +You are given a string s, which contains stars *. |
| 6 | +
|
| 7 | +In one operation, you can: |
| 8 | +
|
| 9 | +Choose a star in s. |
| 10 | +Remove the closest non-star character to its left, as well as remove the star itself. |
| 11 | +Return the string after all stars have been removed. |
| 12 | +
|
| 13 | +Note: |
| 14 | +
|
| 15 | +The input will be generated such that the operation is always possible. |
| 16 | +It can be shown that the resulting string will always be unique. |
| 17 | +
|
| 18 | +Example 1: |
| 19 | +Input: s = "leet**cod*e" |
| 20 | +Output: "lecoe" |
| 21 | +Explanation: Performing the removals from left to right: |
| 22 | +- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e". |
| 23 | +- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e". |
| 24 | +- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe". |
| 25 | +There are no more stars, so we return "lecoe". |
| 26 | +
|
| 27 | +Example 2: |
| 28 | +Input: s = "erase*****" |
| 29 | +Output: "" |
| 30 | +Explanation: The entire string is removed, so we return an empty string. |
| 31 | +
|
| 32 | +Constraints: |
| 33 | +1 <= s.length <= 105 |
| 34 | +s consists of lowercase English letters and stars *. |
| 35 | +The operation above can be performed on s. |
| 36 | + */ |
| 37 | +package com.raj; |
| 38 | + |
| 39 | +public class RemovingStarsFromAString { |
| 40 | + public static void main(String[] args) { |
| 41 | + // Initialization. |
| 42 | + String s = "leet**cod*e"; |
| 43 | + StringBuilder ans = new StringBuilder(s); |
| 44 | + |
| 45 | + // Logic. |
| 46 | + s = getStringWithoutStars(ans); |
| 47 | + |
| 48 | + // Display the result. |
| 49 | + System.out.println("The final string after removing the each * is: " + s); |
| 50 | + } |
| 51 | + |
| 52 | + private static String getStringWithoutStars(StringBuilder s) { |
| 53 | + for (int i = 0; i < s.length(); i++) { |
| 54 | + if (s.charAt(i) == '*') { |
| 55 | + s.delete(i - 1, i + 1); |
| 56 | + return getStringWithoutStars(s); |
| 57 | + } |
| 58 | + } |
| 59 | + return s.toString(); |
| 60 | + } |
| 61 | +} |
0 commit comments