【字符串】C016_面试题 01.06. 字符串压缩(stack 出错 | 双指针)

一、题目描述

Implement a method to perform basic string compression using the counts of repeated characters. 
For example, the string aabcccccaaa would become a2blc5a3. 
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 uppercase and lowercase letters (a - z).

二、题解

方法一:stack

* 一个有趣的错误:字符 10 不能直接用 (char) (10 + '0')
转成字符 10.

public String compressString(String S) {
    int N = S.length();
    if (N <= 2) return S;

    Stack<Character> stack = new Stack<>();
    char[] s = S.toCharArray();
    stack.push(s[0]);
    int cnt = 1;
    for (int i = 1; i < N; i++) {
        if (s[i] != stack.peek()) {
            if (cnt > 0 && cnt < 10) {
                stack.push((char) (cnt + '0'));
                cnt = 1;
            } else {
                stack
            }
            stack.push(s[i]);
        } else {
            cnt++;
        }
    }  
    if (cnt > 0)
        stack.push((char) (cnt + '0'));
    
    StringBuilder sb = new StringBuilder();
    while (!stack.isEmpty()) {
        sb.append(stack.pop());
    }
    if (sb.length() >= N) 
        return S;
    return sb.reverse().toString();
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)

方法二:双指针

算法

  • l,r 维护一个窗口,当 s [ l ] = s [ l ] s[l] = s[l] 时,窗口右边界增加 1.
  • 遇到 s [ l ] ! = s [ r ] s[l] != s[r] 的状态时,开始拼接字符与次数 cnt,cnt 其实就是 r-l 的值。
public String compressString(String S) {
    int N = S.length();
    if (N <= 2) return S;
    char[] s = S.toCharArray();

    StringBuilder sb = new StringBuilder();
    int l = 0,  r = l;
    int cnt = 0;

    while (l < N) {
        while (r < N && s[l] == s[r]) {
            r++;
        }       
        sb.append(s[l]);
        sb.append(r-l);
        l = r; 
    }
    if (sb.length() >= N) 
        return S;
    return sb.toString();
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)
发布了495 篇原创文章 · 获赞 105 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104895236