Skip to content

Commit e374546

Browse files
authored
Merge pull request gzc426#6 from Syuan-Cheng/Syuan-Cheng-patch-5
Create syuan.md
2 parents 19ae39a + 9ebe723 commit e374546

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

2018.11.29-leetcode443/syuan.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
##### 题目
2+
```
3+
给定一组字符,使用原地算法将其压缩。
4+
5+
压缩后的长度必须始终小于或等于原数组长度。
6+
7+
数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。
8+
9+
在完成原地修改输入数组后,返回数组的新长度。
10+
```
11+
##### 思路
12+
设置两个指针i 和 j
13+
i是赋值指针
14+
j用来统计每次字符出现的次数
15+
16+
**难点**
17+
当次数为两位数时的写入
18+
19+
```
20+
char[] temArray=String.valueOf(count).toCharArray();
21+
int k=0;
22+
while (k<temArray.length) {
23+
chars[i++]=temArray[k++];
24+
}
25+
```
26+
一位数时的int和char转换
27+
28+
```
29+
chars[i++]=(char) (count + '0');
30+
```
31+
32+
##### 代码
33+
```
34+
class Solution {
35+
public int compress(char[] chars) {
36+
/**
37+
* 思路:
38+
* 遍历数组 统计每个字符出现的次数
39+
*/
40+
int length=chars.length;//数组长度
41+
if (length<=1) {
42+
return length;
43+
}
44+
45+
46+
int i=0,j=i,count=0;
47+
char temChar=chars[j];
48+
//i是赋值指针
49+
//j是计数指针
50+
while(j<length){
51+
temChar=chars[j];
52+
//个数和temChar相等的字符的个数
53+
while(j<length && chars[j]==temChar){
54+
j++;
55+
count++;
56+
}
57+
//当个数为1时 直接把temChar赋给数组chars
58+
if (count==1) {
59+
chars[i++]=temChar;
60+
}else {
61+
chars[i++]=temChar;
62+
//当个数为一位数
63+
if (count<10) {
64+
chars[i++]=(char) (count + '0');
65+
}else{//当个数大于一位数 借助字符数组
66+
char[] temArray=String.valueOf(count).toCharArray();
67+
int k=0;
68+
while (k<temArray.length) {
69+
chars[i++]=temArray[k++];
70+
}
71+
}
72+
}
73+
count=0;
74+
}
75+
return i;
76+
}
77+
}
78+
```
79+

0 commit comments

Comments
 (0)