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

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

原题链接在这里:

题目:

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.

题解:

计数连续相同char的个数加在后面.

Time Complexity: O(chars.length). Space: O(1).

AC Java:

1 class Solution { 2     public int compress(char[] chars) { 3         if(chars == null || chars.length == 0){ 4             return 0; 5         } 6          7         int mark = 0; 8         int write = 0; 9         for(int i = 0; i

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/8202915.html

你可能感兴趣的文章
2020-11-18
查看>>
Docker面试题(二)
查看>>
一、redis面试题及答案
查看>>
消息队列2
查看>>
C++ 线程同步之临界区CRITICAL_SECTION
查看>>
测试—自定义消息处理
查看>>
MFC中关于虚函数的一些问题
查看>>
根据图层名获取图层和图层序号
查看>>
规范性附录 属性值代码
查看>>
提取面狭长角
查看>>
Arcsde表空间自动增长
查看>>
Arcsde报ora-29861: 域索引标记为loading/failed/unusable错误
查看>>
记一次断电恢复ORA-01033错误
查看>>
C#修改JPG图片EXIF信息中的GPS信息
查看>>
从零开始的Docker ELK+Filebeat 6.4.0日志管理
查看>>
How it works(1) winston3源码阅读(A)
查看>>
How it works(2) autocannon源码阅读(A)
查看>>
How it works(3) Tilestrata源码阅读(A)
查看>>
How it works(12) Tileserver-GL源码阅读(A) 服务的初始化
查看>>
uni-app 全局变量的几种实现方式
查看>>