Open songyy5517 opened 6 months ago
Approach: Loop through the String
Complexity Analysis
class Solution {
public String removeStars(String s) {
// Intuition: Consider StringBuffer as Stack.
// 1. Exception handling
if (s == null || s.length() == 0)
return "";
// 2. Define stack
StringBuffer res = new StringBuffer();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (c == '*' && res.length() != 0)
res.deleteCharAt(res.length() - 1);
else
res.append(c);
}
return res.toString();
}
}
2024/5/21
You are given a string s, which contains stars *. In one operation, you can:
Return the string after all stars have been removed.
Example 1:
Example 2:
Intuition This problem mainly examines String. We need to remove the character before every asterisk. A simple idea is to loop through the string. For each character, if it is a non-asterisk character, then we add it to the StringBuffer; otherwise, we delete the last character in the StringBuffer.