LeetCode 1047. Remove All Adjacent Duplicates In String
原题链接在这里:https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
题目:
Given a string S
of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Example 1:
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Note:
1 <= S.length <= 20000
S
consists only of English lowercase letters.
题解:
Have a StringBuilder working as stack. When the last char of StringBuidler is the same as current char, delete it.
Time Complexity: O(n). n = s.length().
Space: O(n).
AC Java:
1 class Solution { 2 public String removeDuplicates(String s) { 3 if(s == null || s.length() < 2){ 4 return s; 5 } 6 7 StringBuilder sb = new StringBuilder(); 8 for(char c : s.toCharArray()){ 9 if(sb.length() > 0 && sb.charAt(sb.length() - 1) == c){ 10 sb.deleteCharAt(sb.length() - 1); 11 }else{ 12 sb.append(c); 13 } 14 } 15 16 return sb.toString(); 17 } 18 }
Use two points, i and j. j is pointing to current index in s.
i is pointing to result end index.
First arr[i] = arr[j].
When arr[i] == arr[i - 1] then there is a duplicate, set i -= 2.
Time Complexity: O(n).
Space: O(n).
AC Java:
1 class Solution { 2 public String removeDuplicates(String s) { 3 if(s == null || s.length() == 0){ 4 return s; 5 } 6 7 char [] arr = s.toCharArray(); 8 int i = 0; 9 for(int j = 0; j < s.length(); j++, i++){ 10 arr[i] = arr[j]; 11 if(i > 0 && arr[i] == arr[i - 1]){ 12 i -= 2; 13 } 14 } 15 16 return new String(arr, 0, i); 17 } 18 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· Supergateway:MCP服务器的远程调试与集成工具
· C# 13 中的新增功能实操
2018-02-18 LeetCode 399. Evaluate Division
2018-02-18 LeetCode 774. Minimize Max Distance to Gas Station
2018-02-18 LeetCode 360. Sort Transformed Array