首页 > 试题广场 >

字符串压缩功能

[编程题]字符串压缩功能
  • 热度指数:1134 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
利用字符重复出现的次数,实现字符串压缩功能。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)
示例1

输入

"abcccaaaa"

输出

"a1b1c3a4"
遍历字符串的字符,并用一个容器来存储连续的相同字符,这里我使用的是栈。空栈或当前字符与栈顶相同时直接压栈,其他情况就记录当前栈顶字符及其出现次数,并清空栈开始下一轮的连续相同字符的记录。
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param test_string string字符串 输入参数
     * @return string字符串
     */
    public String compressString (String test_string) {
        // write code here
        Stack<Character> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < test_string.length(); i++){
            char c = test_string.charAt(i);
            if(!stack.isEmpty() && stack.peek() != c){
                sb.append(stack.peek()).append(stack.size());
                stack.clear();
            }
            stack.push(c);
        }
        sb.append(stack.peek()).append(stack.size());
        return sb.length() < test_string.length()? sb.toString(): test_string;
    }
}

编辑于 2021-09-01 12:19:13 回复(0)

import java.util.*;

 class Solution {
public String compressString(String test_string) {
        char [] a=test_string.toCharArray(); //转换成字符数组
        if(test_string == "") return ""; 
        int n = test_string.length();
        if(n == 1) return test_string;
        String res = ""; //定义一个字符串
        int p1 = 0;
        int p2 = 1;
        while(p2<n){
            if(a[p1]==a[p2]){
                p2++;
            }else{
                res += a[p1];
                res += p2-p1;
                p1 = p2;
                p2++;
            }
        }
        res += a[p1];
        res += p2-p1;
        int m = res.length();
        if(m >= n) return test_string;
        else return res;
    }
}

发表于 2021-09-08 20:16:30 回复(0)
什么**题啊

编辑于 2024-04-28 18:18:30 回复(0)
这是啥情况啊

发表于 2023-04-22 15:46:39 回复(1)
class Solution:
    def compressString(self , test_string ):
        def compressString(selfSstr) -> str:
            if len(S) == 0:
                return ''
            else:
                a=S[0]
                b=S[0]
                c = 1
                for i in S[1:]:
                    if i == a:
                        c += 1    
                    else:
                        b += str(c)
                        b += i 
                        c = 1
                        a = i
                b += str(c)        
                if len(b) < len(S):
                    return b
                else:
                    return S 
    
发表于 2022-11-10 16:55:37 回复(0)
class Solution:
    def compressString(self , test_string ):
        # write code here滑动窗口:
        left = right = 0
        res = ''
        while right < len(test_string):
            if test_string[right] == test_string[left]:
                right +=1
            else:
                res += test_string[left] + str(right - left)
                left = right
        res += test_string[left] + str(right - left)
        return res if len(res) < len(test_string) else test_string
发表于 2022-09-08 03:17:17 回复(0)
cao  写了忘了提交运行 就直接交卷了 淦
发表于 2022-06-02 18:11:14 回复(0)
class Solution:
    def compressString(self, test_string):
        result = ""
        num = 0
        numl = []
        for i in range(len(test_string)):
            if i == 0:
                result += test_string[0]
                num = 1
            elif test_string[i] != test_string[i-1]:
                result += str(num) + test_string[i]
                num = 1
            else:
                num += 1
                numl.append(num)
                continue

        result += str(num)

        bignum = [item for item in numl if item > 2]
        if len(bignum) > 0 and len(result) < len(test_string):
            return result
        else:
            return test_string

发表于 2022-02-11 18:29:46 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param test_string string字符串 输入参数
     * @return string字符串
     */
    string compressString(string test_string) {
        int n = 1;  // 用来统计相同字符出现的次数
        string res;
        test_string += "_";  // 给字符串一个结尾标记,方便处理
        char c = test_string[0];
        for(int i=1; i<test_string.size(); i++)
        {
            if(c==test_string[i])  n++;  // 前后字符相同
            else{  // 前后字符不同
                // 拼接res
                res += c;
                res += to_string(n);
                // 重新初始化c和n
                c=test_string[i];
                n = 1;
            }
        }
        // 若“压缩”后的字符串没有变短,则返回原先的字符串。
        if(res.size() >= test_string.size()-1){
            test_string.erase(test_string.end() - 1);
            return test_string;
        }
        else{
           return res; 
        }
    }
};

发表于 2021-12-13 22:45:07 回复(0)
a
class Solution:
    def compressString(self , test_string ):
        left, right = 0,0
        strCount = []
        while right < len(test_string):
            if test_string[right] == test_string[left]:
                right +=1
            else:
                strCount.append([test_string[left], right-left])
                left = right
        strCount.append([test_string[left], right - left])
        print(strCount)
        res = ""
        if len(strCount)*2 >= len(test_string):
            res = test_string
        else:
            for c in strCount:
                res += c[0]+str(c[1])
        print(res)
        return res


编辑于 2021-09-04 16:17:33 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param test_string string字符串 输入参数
     * @return string字符串
     */
    string compressString(string test_string) {
        // write code here
        string res;
        char tmp = test_string[0];
        int cnt = 0;
        for(char c:test_string){
            if(c == tmp) cnt ++;
            else{
                res += tmp;
                res += to_string(cnt);
                tmp = c;
                cnt = 1;
            }
        }
        if(cnt > 0) res += tmp,res += to_string(cnt);
        if(res.size() < test_string.size()) return res;
        return test_string;
    }
};

发表于 2021-09-02 15:14:24 回复(0)