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.

  • 相关阅读:
    Java 基础
    Java 数据类型
    Spring 拦截器实现事物
    SSH 配置日记
    Hibernate 知识提高
    Jsp、Servlet
    leetcode 97. Interleaving String
    leetcode 750. Number Of Corner Rectangles
    leetcode 748. Shortest Completing Word
    leetcode 746. Min Cost Climbing Stairs
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12325115.html
Copyright © 2011-2022 走看看