4

我有一个大字符串 char myStr="AAAABBBCCCCCCDDDEFGHHIJJ"。我将把这个字符串传递给我的字符串压缩函数,它应该以以下格式返回字符串 myStr ="A4B3C6D3EFGH2IJ2" 此外,新的字符串替换应该只发生在相同的传递字符串中。无法创建临时数组。

下面是我的函数,我无法找出删除重复项并用同一字符串中的计数替换。

 #include<stdio.h>
 #include<string.h>


 char* StrCompress(char myStr[])
 {
char *s = myStr;
int len = strlen(myStr);
char *in = myStr;
int count =0;
int i=0;


while(*(s) != '\0')
{
    if(*(s)==*(s+1))
    {
        count++;

        if(count == 1)
        {
            in = s;
        }
        s++;

    }
    else
    {
        //myStr[count-1]=count;
        memcpy(in+1,s+1,count);
        s=in;
        count =0;

    }
    i++;
}

return myStr;



}

int main(){

char myStr[] ="AAAABBBCCCCCEEFGIIJJJKLMNNNNOOO";

printf("Compressed String is : %s\n",StrCompress(&myStr));

return 0;

}
4

13 回答 13

4

稍作修改的版本:

char* StrCompress(char myStr[])
{
  char *s, *in;
  for (s = myStr, in = myStr; *s; s++) {
    int count = 1;
    in[0] = s[0]; in++;
    while (s[0] == s[1]) {
      count++;
      s++;
    }   
    if (count > 1) {
      int len = sprintf(in, "%d", count);
      in += len;
    }   
  }
  in[0] = 0;
  return myStr;
}

此外,在使用数组名称调用时,不应使用运算符的地址:

StrCompress(myStr); // not StrCompress(&myStr)

如果您假设一个字符不能重复超过 9 次,那么您可以使用in[0] = '0' + count以下内容代替sprintf

if (count > 1) {
  in[0] = '0' + count;
  in++;
}   
于 2012-12-26T07:37:29.767 回答
2
#include<stdio.h>

char* StrCompress(char myStr[])
{
    char *s = myStr;
    char *r, *p;
    int count, i;

    while (*s)
    {
        /*initially only 1 character of a kind is present*/
        count = 1;

        /*we check whether current character matches the next one*/
        while (*s && *s == *(s+1))
        {
            /*if yes,then increase the count due to the match 
            and increment the string pointer to next */
            count++;
            s++;
        }

        if (count > 1) /*if more than one character of a kind is present*/
        {
            /*assign the value of count to second occurence of a particular character*/
            *(s - count + 2) = count + '0';

            /*delete all other occurences except the first one and second one using array shift*/
            for (i = 0; i < count - 2; i++)
            {
                p = s + 1;
                r = s;

                while (*r)
                    *r++ = *p++;

                s--;
            }
        }
        s++;
    }

    return myStr;
}

int main()
{
    char myStr[] = "AAAABBBCCCCCCDDDEFGHHIJJ";

    printf("Compressed String is : %s\n", StrCompress(myStr));

    return 0;
}
于 2012-12-26T08:15:22.257 回答
1
public static void main(String...args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the String:");
    String str=sc.next();
    int count=1;
    for(int i=0;i<str.length()-1;i++) {
        Character ch1=str.charAt(i);
        Character ch2=str.charAt(i+1);
        if(ch1.equals(ch2)) {
            count++;
        }
        else
        {
            System.out.print((char)(str.charAt(i)));
            if(count>1) {
                System.out.print(count);
            }
            count=1;
        }
        if(i==(str.length()-2)) 
        {
            if(ch1.equals(ch2))
            {System.out.print(ch1+""+count);}
            else {System.out.print(ch2);}
        }
    }
}
于 2020-08-12T06:00:48.083 回答
0
public static String compress(String str) {
    StringBuilder result = new StringBuilder();
    int i = 0;
    int count = 0;
    while(i < str.length() - 1) {
        count++;
        if (str.charAt(i) != str.charAt(i + 1)) {
            result.append(str.charAt(i)).append(count);
            count = 0;
        }
        i++;
    }
    result.append(str.charAt(i)).append(count + 1);
    return result.toString();
}
于 2013-10-11T05:08:38.997 回答
0
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.print("enter the string");
    String s=(new Scanner(System.in)).nextLine();
    String s2=new String("");
    int count=0;

    for(int i=0;i<s.length();i++)
    {
        count=1;



        s2=s2+(s.charAt(i));

        while(i+1<s.length() && s.charAt(i+1)==s.charAt(i)  )
        {
            count++;

            i++;

        }

        s2=s2.concat(count+"");

        }

        System.out.print(s2);
    }

}
于 2015-02-06T08:14:06.330 回答
0

下面是另一个实现,以防万一有人需要它。仅供参考,这种方法称为游程编码

#include <iostream>

void CompressString (std::string str)
{
    //count will keep track of the number of occurences of any given character
    unsigned int count = 1;

    //new string to store the values from the original string
    std::string str2 = "";

    //store the first letter of the string initially
    char ch = str[0];

    //run a loop from the second character of the string since first character if stored in "ch"
    for (unsigned int i = 1; i < str.length(); i++)
    {
        if (str[i] == ch)
            count++;
        else
        {
            str2 = str2 + ch + std::to_string (count);
            ch = str[i];
            count = 1;
        }
    }

    //for cases like aabbb
    str2 = str2 + ch + std::to_string (count);

    //check if after compression, the length of the string reduces or not
    if (str.length() > str2.length())
        std::cout << str2 << std::endl;
    else
        std::cout << str << std::endl;
}

int main ()
{
    std::cout << "Enter a string to compress: ";
    std::string str;
    getline (std::cin, str);

    std::cout << "Compressed string is: ";
    CompressString (str);
    return 0;
}
于 2016-02-04T04:50:58.690 回答
0

这是另一个就地 java 程序。我们可以使用 StringBuilder 代替字符串

public static void main(String[] args) {

    String a = "aaabbccaaaddj";


        for(int i=0;i<a.length();i++){
            int c=i+1;
            int duplicateCharCount=1;
            while(c<a.length()&&a.charAt(c)==a.charAt(i)){
                ++c;
                ++duplicateCharCount;
            }

                a=a.substring(0,i+1)+duplicateCharCount+a.substring(i+duplicateCharCount);
                i++;


        }
        System.out.println(a);
    }
于 2016-10-21T14:15:18.860 回答
0
public class StringCompression {
    public static String compress(String str) {
        StringBuilder result = new StringBuilder();
        int i;
        int count = 0;
        for(i=0; i< str.length() - 1;i++,count++) {
            if (str.charAt(i) != str.charAt(i + 1)) {
                result.append(str.charAt(i)).append(count);
                count = 0;
            }
        }

        result.append(str.charAt(i)).append(count);
        return result.toString();
    }

    public static void main(String[] args) {
        String string = "aaassssdddaaaggghhhfgreeeeeeedrrrrr";
        String x= compress(string);
        System.err.println(x);
    }
}
于 2018-03-10T17:31:25.563 回答
0
#include<stdio.h>
#include<conio.h>

char* compress(char* str);

int main(){
  clrscr();
  char str[1000];
  scanf("%[^\n]s", str);
  char* s = compress(str);
  printf("\n%s", s);
  getch();
  return 0;
}

char* compress(char* str){
 char* s = str;
 int count = 1;
 char str2[1000] = "\0";
 char* n = str2;
 while(*(s) != '\0'){
    if(count == 1){
      *n = *s;
      n++;
    }
    if(*(s) == *(s+1)){
      count++;
      s++;
    }
    else{
     *n = '0' + count;
     n++;
     count = 1;
     s++;
    }
}
 return str2;
}
于 2019-10-11T12:04:48.570 回答
0

这是 ES6 的另一个解决方案:

    // aaeezaa : a4e2z1
    function compressString(str) {
        const obj = {};
        const sortedArr = [...str].sort();

        for(i = 0; i<sortedArr.length; i++) {
            let c = 1;

            while((sortedArr[i] === sortedArr[i+1]) && sortedArr[i+1]) {
                c++;
                i++;
            }

            obj[sortedArr[i]] = c;
        }

        return Object.keys(obj).reduce((compressedStr, k) => compressedStr + k + obj[k], '');
    }
于 2019-12-03T11:06:40.980 回答
0

我做了两个假设并编写了这段代码,

  1. 我们的空间是我们正在编码的字符串大小的两倍。即,假设我们正在编码“ab”,那么分配的空间空间应该至少为 4 个字节。

  2. 字母的连续条纹最多可以是 999。如果有可能在相邻位置有 1000 个相同的字符,那么我们必须相应地增加“count_str”字符数组的大小。

    #include <stdio.h>
    #include <string.h>

    char *compress(char *input)  {

        int i = 0;

        int count = 1;

        int k = 0;

        int j = 0;

        int len = 0; 

        int digits_in_count = 0;

        char count_str[3];

        int m = 0;

        for(i = 0; i < strlen(input); i++) {

            j = i+1;

            m = 0;

            count = 1;

            len = strlen(input);

            printf("\niteration: %d, string = %s",i, input);

            while((input[j] != '\0') && (input[j] == input[i])) {
                count++;
                j++;
            }

            sprintf(count_str, "%d", count);

            digits_in_count = strlen(count_str);

            //this means we have reaced last alphabet in the string
            if(input[j] == '\0' && count == 1) {

                k = k+1;
                goto count_append;

            }

            input[k++] =  input[i];

            // we are assuming that we have enough space in the end, to move string.
            // we are memmove for remaining portion of the string.
            // if the string is "aaab", then we have to move 'b' one step ahead 
            // and it will look like "aab", later in the end we are adding count,
            // and making it as "a3b".
            // if the string is "ab", then we have to move 'b' one step away,
            // to make space for adding 'count'.
            // and the new string after memmove will looklike "abb",
            // in the end we are adding count and making it as "a1b"
            // memmove will not hit for last character in the string, because there
            // is already enough space for appending 'count'.
            memmove((input+i+digits_in_count+1) , input+j, len-j+1);

            i = i+digits_in_count;

            count_append:
            {
                while(digits_in_count) {

                    input[k++] =  *(count_str+m);

                    m = m+1;
                    digits_in_count--;

                }
            }

        }   

        return input;

    }

    void main()
    {
        char arr[50] = "aaab";
        printf("\n%s\n", compress(arr));
    }
于 2020-05-26T05:38:18.137 回答
0
void gen_compressed_str(string str){ 
        int len = str.length(); 
        for (int i = 0; i < len; i++) { 
  
        int count = 1; 
        while (i < len - 1 && str[i] == str[i + 1]) { 
            count++; 
            i++; 
        }
        if (count == 1){
          cout << str[i];
        }
        else{
          cout << str[i]<<count;
        }
         
    } 
    cout<<endl;
}
于 2020-07-25T16:35:38.070 回答
0
void stringCompression(char a[]) {
    int i, count=1,j=0;
    for(i=0;a[i]!='\0';i++){
        if(a[i]==a[i+1]){
            count++;
        }
        else if(a[i]!=a[i+1]){
            if(count>1){
                a[j++]=a[i];
                a[j++]=(char)(48+count);
            }
            else if(count==1){
                a[j++]=a[i];
            }
            count=1;
        }
    }
    a[j]='\0';
}
于 2020-09-19T15:49:13.540 回答