天天看点

【程序员面试金典】 06 字符串压缩

题目

字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

题解

解题思路:使用StringBuilder拼接字符串

public class Solution {
    public string CompressString(string S) {
        if (string.IsNullOrEmpty(S))
        {
            return S;
        }
        
        StringBuilder resultSB = new StringBuilder();
        int count =1;
        char last = S[0];
        for (int i=1; i<S.Length; ++i)
        {
            if (last!=S[i])
            {
                resultSB.Append(last).Append(count);
                count =1; 
                last= S[i];
            }
            else
            {
                count++;
            }
        }

        string compress = resultSB.Append(last).Append(count).ToString();
        return compress.Length<S.Length?compress:S;
    }
}      

知识点

String.IsNullOrEmpty(s)

执行效果