zoukankan      html  css  js  c++  java
  • 213. String Compression【easy】

    Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.

    If the "compressed" string would not become smaller than the original string, your method should return the original string.

    You can assume the string has only upper and lower case letters (a-z).

     
    Example

    str=aabcccccaaa return a2b1c5a3
    str=aabbcc return aabbcc
    str=aaaa return a4

    解法一:

     1 public class Solution {
     2     /**
     3      * @param str a string
     4      * @return a compressed string
     5      */
     6     public String compress(String str) {
     7         // Corner case
     8         if (str == null) {
     9             return null;
    10         } else if (str.length() <= 2) {
    11             return str;
    12         }
    13         
    14         StringBuilder sb = new StringBuilder();
    15         char temp = str.charAt(0);
    16         int count = 1;
    17         
    18         for (int i = 1; i < str.length(); i++) {             
    19            // If same char continues, then add the count             
    20            if (str.charAt(i) == temp) {                 
    21                count++;             
    22            } else {                   
    23            // Encounter different char, set temp to the char and count to 1       
    24               sb.append(temp);                 
    25               sb.append(count);                 
    26               temp = str.charAt(i);                 
    27               count = 1;             
    28            }         
    29        }                  
    30 
    31       // Do not forget the last char and the count!!!           
    32       sb.append(temp).append(count);                  
    33 
    34       // Compare the result of original str with the new stringbuilder            
    35       if (sb.length() >= str.length()) {
    36             return str;
    37       } else {
    38             return sb.toString();
    39       }
    40    }
    41 }

    Here we use StringBuilder to create a new String, instead of String concatenation. That’s because for String concatenation operation, it’ll build a new string for every operation.

    The basic algorithm is:
    1、Create stringbuilder and initialize the first temp char, with count = 1
    2、Go through the string char by char
    (1)If char(i) equals to temp, continue and add count
    (2)If not, add the temp and count to stringbuilder, reset the temp to be char(i) and count to be 1
    3、Go out of the loop and add the last char and count for it
    4、Compare the stringbuilder with initial str

    Note: After go through the for loop, the temp is equals the last - 1 char, so we need to add the last char with its count.

    Time complexity: O(n)
    Space complexity: O(n)

    参考@Steven Wu 的代码

    https://codebysteven.wordpress.com/2016/03/14/lintcode-string-compression/

    解法二:

     1 public class Solution {
     2     /*
     3      * @param str: a string
     4      * @return: a compressed string
     5      */
     6     public String compress(String str) {
     7         if (str == null || str.length() < 3) {
     8             return str;
     9         }
    10         StringBuilder sb = new StringBuilder();
    11         Map<Character, Integer> map = new HashMap<>();
    12         char pre = str.charAt(0);
    13         map.put(pre, 1);
    14         for (int i = 1; i < str.length(); i++) {
    15             char cur = str.charAt(i);
    16             if (cur == pre) {
    17                 map.put(pre, map.get(pre)+1);
    18             } else {
    19                 sb.append(pre);
    20                 sb.append(map.get(pre));
    21                 map.put(pre, 0);
    22                 map.put(cur, 1);
    23                 pre = cur;
    24             }
    25         }
    26         sb.append(pre);
    27         sb.append(map.get(pre));
    28         String res = sb.toString();
    29         return res.length() < str.length() ? res : str;
    30     }
    31 }

    参考@linspiration 的代码

    https://segmentfault.com/a/1190000012634492

  • 相关阅读:
    IP掩码的作用
    linux shell 笔记
    ubuntu apt-get Failed to fetch Temporary failure resolving 'security.ubuntu.com'
    ubuntu 16.04 & 18.04 远程桌面使用
    取消Ubuntu开机硬盘自检
    linux shell 脚本输入参数解析
    Ubuntu 16.04 + python3 源码 安装+使用labelImg最新版
    用tinyxml2读写xml文件_C++实现
    常用工具问题及解决方案
    可视化调试工具
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8150515.html
Copyright © 2011-2022 走看看