zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    centos7 安装 tesseract4.1
    08 图的数据结构和算法
    07 树形结构及其算法
    05 数组与链表算法
    06 堆栈与队列算法
    04 查找与哈希算法
    03 排序算法
    javascript 标签轮播
    tomcat URI get 参数中文传到后台 乱码 URIEncoding
    javascript 标签切换
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12325115.html
Copyright © 2011-2022 走看看