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. 1 <= S.length <= 20000
  2. 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 }
复制代码

跟上Remove All Adjacent Duplicates in String II.

posted @   Dylan_Java_NYC  阅读(369)  评论(0编辑  收藏  举报
编辑推荐:
· .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
点击右上角即可分享
微信分享提示