zoukankan      html  css  js  c++  java
  • 字符串压缩

    问题描述:
    将给定的字符串,按照规格压缩,Inplace压缩字符串
    压缩规格为:相同字符连续,则压缩为“字符+数字个数”,如”aaaa”压缩为”a4

    第一个想法是如果都为非重复字符的话,如abc,则编码后岂不是要a1b1c1,占用空间是之前的2倍,达不到压缩的目的,所以应该默认为1的不输出,按照这个思路,在原字符串上进行替换。

    第二个想法是如果字符超过10个,即count对于的字符数字大于1个,又该如何,原博文并未处理。细想起来,这里隐含这itoa的转换,但itoa转换的字符序为倒序,需要reverse一下。

     

    如下是最终的实现版本。

      size_t InplaceCompress(char* str) {
        char* first = str;
        char* last = str;
        int count = 0;
        while(*last) {
         while(*first == *++last ) {
          ++count;
         }
         printf("%c\t%d\n", *first, count);
         // todo 
         if (count > 0) {
          char* begin =  first + 1;
          ++count;
          while (count) {
           *++first = '0'+ count%10;
           count /= 10;
          }
          char* end = first;
          while (begin < end) {
            std::swap(*++begin, *--end);
          }
         }
         *++first = *last;
         count = 0;
        }
        *++first ='\0';
        return first - str;
    }

     

  • 相关阅读:
    leetcode — simplify-path
    leetcode — climbing-stairs
    leetcode — sqrtx
    leetcode — text-justification
    leetcode — add-binary
    leetcode — plus-one
    leetcode — valid-number
    leetcode — minimum-path-sum
    leetcode — unique-paths-ii
    四维偏序 CDQ套CDQ
  • 原文地址:https://www.cnblogs.com/westfly/p/2967000.html
Copyright © 2011-2022 走看看