博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
443. String Compression - Easy
阅读量:6706 次
发布时间:2019-06-25

本文共 1734 字,大约阅读时间需要 5 分钟。

Given an array of characters, compress it .

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array , return the new length of the array.

 

Follow up:

Could you solve it using only O(1) extra space?

 

Example 1:

Input:["a","a","b","b","c","c","c"]Output:Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]Explanation:"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

 

Example 2:

Input:["a"]Output:Return 1, and the first 1 characters of the input array should be: ["a"]Explanation:Nothing is replaced.

 

Example 3:

Input:["a","b","b","b","b","b","b","b","b","b","b","b","b"]Output:Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].Explanation:Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".Notice each digit has it's own entry in the array.

 

Note:

  1. All characters have an ASCII value in [35, 126].
  2. 1 <= len(chars) <= 1000.

 

双指针+一个常数用来计数

时间:O(N),空间:O(1)

class Solution {    public int compress(char[] chars) {        int resIdx = 0, idx = 0;        while(idx < chars.length) {            char cur = chars[idx];            int cnt = 0;            while(idx < chars.length && cur == chars[idx]) {                idx++;                cnt++;            }            chars[resIdx++] = cur;            if(cnt != 1) {                for(char c : Integer.toString(cnt).toCharArray()) {                    chars[resIdx++] = c;                }            }        }        return resIdx;    }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10014661.html

你可能感兴趣的文章
JSP内置对象(9种)
查看>>
mysql数据库重复记录过滤删除解决
查看>>
Maven的eclipse插件
查看>>
Java 二进制
查看>>
懒得理病毒的免疫系统能救命
查看>>
Java内存分析 --- 虚拟机运行时数据区
查看>>
关于mac android studio 与svn 解除关联后 无法再次share (Subversion) 的解决办法
查看>>
如何添加windows 系统的逻辑磁盘并设置盘符
查看>>
Vmware workstation与Hyper-v不兼容解决方法
查看>>
shell select case
查看>>
linux下IPTABLES配置详解
查看>>
openstack安装(liberty)--环境准备
查看>>
内网邮件服务器映射,防火墙设置
查看>>
我的友情链接
查看>>
Mock.js的使用
查看>>
Linux部署ThinkPHP 验证码不显示
查看>>
bootstrap多个modal模态框同时设置垂直居中的方法
查看>>
设置grub密码
查看>>
mydumper安装笔记
查看>>
secure CRT 串口自动烧录程序
查看>>