zoukankan      html  css  js  c++  java
  • 重复字符的压缩

      对输入字符串进行压缩,输入"aaabcccdde",输出"3ab3c2de",即对连续出现的字符进行压缩。

      解题思路:首先创建一个临时变量temp,给它赋值为第一个字符的值,从下一个字符开始遍历,如果等于temp,count++;如果不等于temp;则把此时temp出现的次数和temp存放在字符数组b中。(输出也行,不会多占用内存空间,空间复杂度为O(1)).

    #include <iostream>
    #include <cstring>
    #include <cstdlib>
    using namespace std;
    char* stringCompress(char a[])
    {char temp=a[0];
        int len=strlen(a);
        //int count[len]={0};
        int count=1;
        //string str;
        char b[len+1];
        int j=0;
        for(int i=1;i<len;i++)
        {
            if(a[i]==temp)
                count++;
            else{
                if(count!=1)
                  b[j++]=count+'0';
                 b[j++]=temp;
                 count=1;
                temp=a[i];
            }
        }
        if(count!=1)
          b[j++]=count+'0';
        b[j]=temp;
        b[++j]='';
    
        return b;
    }
    int main()
    {
        char a[100];
        cin.getline(a,100);
        cout<<a<<endl;
    
        char* res=stringCompress(a);
        cout<<res<<endl;
        system("pause");
        return 0;
    }

    直接输出不再占用多余的内存空间,代码如下:

    void stringCompress(char a[])
    {
        //int mark=0;
        char temp=a[0];
        int len=strlen(a);
        //int count[len]={0};
        int count=1;
        //string str;
        char b[len+1];
        int j=0;
        for(int i=1;i<len;i++)
        {
            if(a[i]==temp)
                count++;
            else{
                if(count!=1)
                  cout<<count;
                 cout<<temp;
                 count=1;
                temp=a[i];
            }
        }
        if(count!=1)
          cout<<count;
        cout<<temp;
    }
  • 相关阅读:
    gitlab安装笔记二_Centos7配置163yum源
    gitlab安装笔记一_虚拟机中安装Centos7
    初篇:我与Linux
    Redis分布式锁正确的实现方法
    MacOS从零开始搭建hexo博客
    docker服务编排--docker-compose
    多线程问题整理
    maven依赖范围
    linux打开文件数 too many open files 解决办法
    【数据结构】队列-数组模拟队列
  • 原文地址:https://www.cnblogs.com/wft1990/p/6953409.html
Copyright © 2011-2022 走看看