• 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.

    题解:

    Follow the instructions, and remove 2 consecutive same chars.

    Time Complexity: O(n^2). n = S.length().

    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         boolean changed = true;
     8         while(changed){
     9             changed = false;
    10             StringBuilder sb = new StringBuilder();
    11             int i = 0;
    12             while(i < S.length()){
    13                 if(i == S.length() - 1 || S.charAt(i) != S.charAt(i + 1)){
    14                     sb.append(S.charAt(i));
    15                     i++;
    16                 }else{
    17                     changed = true;
    18                     int j = i + 1;
    19                     int count = 1;
    20                     while(j < S.length() && S.charAt(i) == S.charAt(j) && count < 2){
    21                         j++;
    22                         count++;
    23                     }
    24                     
    25                     i = j;
    26                 }
    27             }
    28             
    29             S = sb.toString();
    30         }
    31         
    32         return S;
    33     }
    34 }

    跟上Remove All Adjacent Duplicates in String II.

  • 相关阅读:
    static、final、this、super关键
    细节二:参数、引用类型、实例化
    枚举类型
    单例模式
    细节一:字符串、switch、默认值、数组
    类属性和类方法
    装饰器模式
    TreeSet
    可见参数和增强for以及自动拆装箱
    静态导入
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12325115.html
Copyright © 2020-2023  润新知