zoukankan      html  css  js  c++  java
  • 字符串压缩 牛客网 程序员面试金典 C++ Python

    字符串压缩 牛客网 程序员面试金典 C++ Python

    • 题目描述

    • 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。

    • 给定一个string iniString为待压缩的串(长度小于等于10000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。

    • 测试样例

    • "aabcccccaaa"

    • 返回:"a2b1c5a3"

    • "welcometonowcoderrrrr"

    • 返回:"welcometonowcoderrrrr"

    C++

    class Zipper {
    public:
        //run:7ms memory:608k
        string zipString(string iniString){
            string str;
            int i = 0;
            int j = 0;
            while(i < iniString.length()){
                while(iniString[i] == iniString[j]) i++;
                str += iniString[j];
                str += to_string(i-j);
                j = i;
            }
            if(iniString.length() < str.length()) return iniString;
            else return str;
        }
    };

    Python

    class Zipper:
        #run:38ms memory:5732k
        def zipString(self,iniString):
            temp = iniString[0]
            counter = 0
            ret = ''
            for x in iniString:
                if x == temp:
                    counter += 1
                else:
                    ret += str(temp) + str(counter)
                    temp = x
                    counter = 1
            ret += str(temp) + str(counter)
            if len(ret) > len(iniString):
                return iniString
            else:
                return ret
  • 相关阅读:
    Java io流 之file类(文件和文件夹)
    异常处理
    封装
    面向对象与类
    包与模块的使用
    模块
    递归函数
    迭代器
    装饰器
    函数基础2
  • 原文地址:https://www.cnblogs.com/vercont/p/10210326.html
Copyright © 2011-2022 走看看