首页 > 试题广场 >

压缩字符串(一)

[编程题]压缩字符串(一)
  • 热度指数:9187 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2bc5a3。
1.如果只有一个字符,1不用写
2.字符串中只包含大小写英文字母(a至z)。

数据范围:
0<=字符串长度<=50000

要求:时间复杂度O(N)
示例1

输入

"aabcccccaaa"

输出

"a2bc5a3"
示例2

输入

"shopeew"

输出

"shope2w"
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        char[] cs = param.toCharArray();
        StringBuilder res = new StringBuilder();
        int count = 1;
        for(int i = 0; i < cs.length-1; i++){
            if(cs[i] == cs[i+1]){
                count++;
            }else{
                res.append(cs[i]);
                if(count > 1) res.append(count);
                count = 1;
            }
        }
        // 判断最后的字符
        res.append(cs[cs.length-1]);
        if(count > 1) res.append(count);
        return res.toString();
    }
}

发表于 2021-09-01 23:51:00 回复(3)
#include <stdio.h>
char* compressString(char* param ) {
    int i=0,n=1,j=0;
    char* out=param;
    for (i=0;i<strlen(param);i++)
    {
        if(param[i]==param[i+1])
            {n+=1;}
        else{
            if(n==1){
                out[j]=param[i];
                j+=1;
            }
            else{
                out[j]=param[i];
                out[j+1]='0'+n;
                j+=2;//因为最后j=j+2,所以最后拷贝的时候申请j个字符大小的内存
            }
            n=1;
        }
    }
    char *res=(char*)malloc(j*sizeof(char));
    strncpy(res,out,j);
    return res;
}
C,请多指教

发表于 2021-08-30 22:37:46 回复(0)
8岁李琛做法:
public static String compressString(String param) {
        // write code here
        if (param.length() < 2) return param;
        int repeat = 1;
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < param.length() - 1; i++) {
            if (param.charAt(i) == param.charAt(i + 1))
                repeat++;
            else {
                res.append(param.charAt(i)).append(repeat > 1 ? repeat : "");
                repeat = 1;
            }
        }
        // 处理最后一个字符,包含1个重复和多个重复
        res.append(param.charAt(param.length() - 1)).append(repeat > 1 ? repeat : "");
        return res.toString();
    }


发表于 2024-06-15 08:29:37 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param param string字符串
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        StringBuilder sb = new StringBuilder();
        char arr[] = param.toCharArray();

        int temp = 1;//定义临时变量temp
        for (int i = 0; i < arr.length; i++) {
            if (i + 1 < arr.length && arr[i + 1] == arr[i]) {
                //后一个和当前相等时并且需要满足i+1不能溢出,temp+1
                temp++;
            } else {//不满足上述条件后判断temp,大于1直接加在后边,否则不加temp
                if (temp > 1) {
                    sb.append(arr[i]).append(temp);
                    temp = 1;//还原temp的值
                } else {
                    sb.append(arr[i]);
                }
            }
        }
        return sb.toString();
    }
}

发表于 2022-10-05 19:26:32 回复(0)
很简单,一边遍历一边计数。保存上一个字符用来对比当前字符,如果计数超过1就追加字符+计数,否则只追加字符。
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        if(params.length() == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        char prevChar = param.charAt(0);
        int count = 1;
        for(int i = 1; i < param.length(); i++){
            char curChar = param.charAt(i);
            if(prevChar == curChar){
                count += 1;
            }else{
                if(count > 1)
                    sb.append(prevChar).append(count);
                else
                    sb.append(prevChar);
                prevChar = curChar;
                count = 1;
            }
        }
        if(count > 1)
            sb.append(prevChar).append(count);
        else
            sb.append(prevChar);
        return sb.toString();
    }
}

编辑于 2022-02-21 17:18:38 回复(2)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param param string字符串
# @return string字符串
#
class Solution:
    def compressString(self , param: str) -> str:
        # write code here
        n = len(param)
        param = list(param)
        read = write = 0
        while read < n:
            cur = param[read]
            # print(cur)
            cnt = 0
            while read < n and  param[read] == cur:
                cnt += 1
                read += 1
            param[write] = cur
            write += 1
            if cnt > 1:
                for i in str(cnt):
                    param[write] = i
                    write += 1
                # write+=1
        return "".join(param[:write])
           
             
           


发表于 2025-06-27 12:36:18 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param param string字符串
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        char[] c = param.toCharArray();
        if(c.length < 2){
            return param;
        }
        StringBuilder sb = new StringBuilder();
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < c.length; i++) {
            if (map.isEmpty()) {
                map.put(c[i], 1);
            } else if (map.get(c[i]) == null) {
                sb.append(c[i - 1]);
                if (map.get(c[i - 1]) > 1) {
                    sb.append(map.get(c[i - 1]));
                }
                map.clear();
                map.put(c[i], 1);
            } else {
                map.put(c[i], map.get(c[i]) + 1);
            }
        }
        sb.append(c[c.length - 1]);
        if (map.get(c[c.length - 1]) > 1) {
            sb.append(map.get(c[c.length - 1]));
        }
        return sb.toString();
    }
}

发表于 2024-10-22 15:30:37 回复(0)
 
    string compressString(string param) {
        // write code here
        string s;
        int num=param.length();
        for(int i=0;i<num;){
            int j=i+1;
            int count=1;
            while(param[i]==param[j]){
                j++;
                count++;
            }
            if(count==1){
                s+=param[i];
                i++;
            }
            else{
                i=j;
                s+=param[i-1];
                s+=to_string(count);
            }
        }
        return s;
    }

发表于 2024-09-16 15:03:49 回复(0)
菜坤只能想到这个笨办法了,新建两个数组,一个记录字符,一个记录该字符重复的次数,然后新建一个空字符串,按照题目要求把上面两个数组中的数据一个一个的拼接到字符串上。
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    public String compressString (String param) {
        if (param.equals("")){
            return "";
        }
        int[] arr=new int[param.length()];
        char[] ch=new char[param.length()];
        int n=0;
        String str="";
        ch[0]=param.charAt(0);
        for (int i=0;i<param.length()-1;i++){
            if (param.charAt(i+1)==param.charAt(i)){
                arr[n]++;
            } else{
                n++;
                ch[n]=param.charAt(i+1);
            }
        }
        for (int i=0;i<=n;i++){
            if (arr[i]==0){
                str=str+ch[i];
            }else{
                str=str+ch[i]+(arr[i]+1);
            }
        }
        return str;
    }
}


发表于 2024-08-25 10:10:37 回复(0)

双指针

用i和j维护一个相同字符的区间[i, j)(左闭右开区间),然后它们的差值就是字符的个数。

用j遍历字符串,i始终指向区间的下一个字符。首先用x保存第一个字符,然后用while循环找到右边界j。如果字符个数是1,只向答案字符串中加入字符,否则加入字符和数字。

注意while (x == param[++j])是前置++,因为i是这个区间的第一个字符,j应该从它的下一个开始。由于是左闭右开区间,所以j-i不用+1就能表示区间中的字符个数。

代码

class Solution {
public:
    string compressString(string param) {
        string s;
        int n = param.size();
        int i = 0, j = 0;
        while (j < n)
        {
            char x = param[i];
            while (x == param[++j]);
            if (j - i == 1) s += x;
            else if (j - i > 1) s += x, s += to_string(j - i);
            i = j;
        }
        return s;
    }
};
  • 时间复杂度:
  • 空间复杂度:
发表于 2024-07-27 20:22:05 回复(0)
 char [] chars = param.toCharArray();
        String s = "";
        for (int i = 0; i < param.length(); i++) {
            int num = 1;
            int j = i;
            while (j < param.length() - 1 && chars[j] == chars[j + 1]) {
                ++num;
                j++;
            }
            i = j;
            s = s + chars[i];
            if (num != 1) {
                s = s + String.valueOf(num);
            }

        }
        return s;

编辑于 2024-03-02 18:38:05 回复(0)
滑!
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        StringBuilder sb = new StringBuilder();
        int start = 0;
        int end = 0;
        while(end < param.length()) {
            if(start == end) {
                sb.append(param.charAt(start));
                end++;
            }
            else {
                if(param.charAt(end) == param.charAt(start)) {
                    end++;
                }
                if((end >= param.length()) || (param.charAt(end) != param.charAt(start)) ) {
                    if(end - start != 1) sb.append(Integer.valueOf(end - start));
                    start = end;
                }
            }
        }
        return sb.toString();
    }
}

发表于 2024-01-14 10:29:55 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    public String compressString (String param) {
        if (param.length() <= 1) {
            return param;
        }
        int left = 0;
        int right = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < param.length(); i++) {
            if (param.charAt(left) == param.charAt(right)) {
                right++;
            } else {
                sb.append(param.charAt(left));
                if (right - left != 1) {
                    sb.append(right - left);
                }
                left = right;
                right++;
            }
        }
        sb.append(param.charAt(left));
        if (right - left != 1) {
            sb.append(right-left);
        }
        return sb.toString();
            
        
        
    }
}

发表于 2023-11-24 20:16:48 回复(1)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        char[] str_list = param.toCharArray();
        // 新建一个拼接字符串
        StringBuilder sb = new StringBuilder();
        if(str_list.length==0)return sb.toString();
        // point是数组下标
        int point = 0;
        // num是对用下表的数字出现多少次
        int num = 1;
        while(point<str_list.length-1){
            // 统计下标和出现此处
            if(str_list[point] == str_list[point+1]){
                point++;
                num++;
                // 如果只出现1次则不拼接1
            }else if(str_list[point] != str_list[point+1] && num == 1){
                sb.append(str_list[point]);
                point++;
                num=1;
                // 如果出现多次,则拼接相应个数
            }else if(str_list[point] != str_list[point+1] && num != 1){
                sb.append(str_list[point]).append(num);
                point++;
                num=1;
            }
        }
        // 追加最后一个字母
        if(num ==1){
            sb.append(str_list[str_list.length-1]);
        }else{
             sb.append(str_list[str_list.length-1]).append(num);
        }
       
        return sb.toString();
    }
}

发表于 2023-06-08 21:02:42 回复(0)
#include <string>
class Solution {
public:
    string compressString(string param) {
        // write code here
        string res = "";
        int count = 1;
        for (int i = 1; i < param.length(); i++) {
            if (param[i] == param[i - 1]) {
                count++;
            } else {
                if (count == 1) {
                    res += param[i - 1];
                } else {
                    res += param[i - 1] + to_string(count);
                }
                count = 1;
            }
        }
        if (count == 1) {
            res += param[param.length() - 1];
        } else {
            res += param[param.length() - 1] + to_string(count);
        }

        return res;
    }
};
#include <string>
class Solution {
public:
    string compressString(string param) {
        string res = "";
        int count = 1;
        for (int i = 1; i < param.length(); i++) {
            if (param[i] == param[i - 1]) {
                count++;
            } else {
                res += param[i - 1];
                if (count > 1) {
                    res += to_string(count);
                }
                count = 1;
            }
        }
        res += param[param.length() - 1];
        if (count > 1) {
            res += to_string(count);
        }

        return res;
    }
};
#include <string>
class Solution {
public:
    string compressString(string param) {
        string res = "";
        param += " ";
        int count = 1;
        for (int i = 1; i < param.length(); i++) {
            if (param[i] == param[i - 1]) {
                count++;
            } else {
                res += param[i - 1];
                if (count > 1) {
                    res += to_string(count);
                }
                count = 1;
            }
        }    

        return res;
    }
};


发表于 2023-05-13 11:54:27 回复(0)
package main
import _"fmt"
import "strconv"
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param param string字符串 
 * @return string字符串
*/
func compressString( param string ) string {
    if len(param)==0{
        return ""
    }
    ans:=""
    pre:=param[0]
    cnt:=1
    for i:=1;i<len(param);i++{
        if param[i]==pre{
            cnt++
        }else{
            ans+=string(pre)
            if cnt>1{
                ans+=strconv.Itoa(cnt)
            }
            pre=param[i]
            cnt=1
        }
    }
    ans+=string(pre)
    if cnt>1{
        ans+=strconv.Itoa(cnt)
    }
    return ans
}

发表于 2023-03-06 21:30:41 回复(0)
public class CompressString {
	public String compressString(String param) {
		// write code here
		if (param == null || param.length() == 0) {
			return "";
		}
		String returnString = "";
		char[] chars = param.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			char temp = chars[i];
			int count = 1;
			int nextIndex = 0;
			for (int j = i + 1; j < chars.length; j++) {
				if (temp == chars[j]) {
					count++;
					if (j == chars.length - 1) {
						nextIndex = chars.length;
					}
					continue;
				} else {
					nextIndex = j - 1;
					break;
				}
			}
			if (count == 1) {
				returnString += String.valueOf(temp);
			} else {
				returnString += (String.valueOf(temp) + count);
				
			}
			if (nextIndex != 0 && nextIndex != chars.length - 1) {
				i = nextIndex;
			}
		}
		return returnString;
	}
}

发表于 2022-10-09 13:23:22 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param param string字符串
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        if (param.equals("")) return "";
        StringBuffer sb = new StringBuffer();
        int i = 0, j = 0;
        for (; j < param.length(); j ++) {
            if (param.charAt(j) == param.charAt(i)) {
                continue;
            } else {
                sb.append(param.charAt(i));
                if (j - i != 1) {
                    sb.append(j - i);
                }
                i = j;
            }
        }
        sb.append(param.charAt(i));
        if (j - i != 1) {
            sb.append(j - i);
        }
        return sb.toString();
    }
}

发表于 2022-09-12 21:27:23 回复(0)
char* compressString(char* param ) {
    // write code here
    int len=strlen(param);
    int i,j,n=1,len_s;  
    char *result=(char*)calloc(len, sizeof(char));
    result[0]=param[0];
    for(i=1,j=1;i<=len;i++)
    {
        if(param[i]==param[i-1]) n=n+1;
        else 
        {
            if(n>1)
            {
                char *s=(char*)calloc(6, sizeof(char));
                for(int k=0;n;k++)
                {
                   s[k]='0'+n%10;
                    n=n/10;
                }
                n=1;
                len_s=strlen(s);
                for(;len_s;len_s--,j++)
                {
                    result[j]=s[len_s-1];
                }
                free(s);
            }
            result[j]=param[i];
            j++;        
        }
    }
    return result;
}
发表于 2022-08-31 21:46:10 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    string compressString(string param) {
        // write code here
        int n = param.length();
        string str = "";
        int num = 1;
        str += param[0];
        for(int i=1; i<n; i++)
        {
            if(param[i] != param[i-1])
            {
                if(num==1)
                    str += param[i];
                else
                {
                    stack<int> stc;
                    while(num)
                    {
                        stc.push(num % 10);
                        num = num / 10;
                    }
                    while(!stc.empty())
                    {
                        int val = stc.top();
                        stc.pop();
                        str += val + '0';
                    }
//                     str+=num + '0';
                    num=1;
                    str+= param[i];
                }
            }
            else
                num++;
        }
        if(num > 1)
        {
            stack<int> stc;
            while(num)
            {
                stc.push(num % 10);
                num = num / 10;
            }
            while(!stc.empty())
            {
                int val = stc.top();
                stc.pop();
                str += val + '0';
            }
        }
        return str;
    }
};

发表于 2022-08-10 11:07:48 回复(0)