题目标签:String
这一题需要3个pointers:
anchor:标记下一个需要存入的char
read:找到下一个不同的char
write:标记需要存入的位置
让 read指针 去找到下一个char,找到后先把 anchor 位置上的 char 存入 write 位置, 然后把 char 重复的次数 转化为 char 存入下一个位置,最后重新设定 anchor = read + 1。
Java Solution:
Runtime beats 26.91%
完成日期:10/09/2018
关键词:3个指针
关键点:如果char 重复的次数大于9,需要把 int 转换为 char
1 class Solution 2 { 3 public int compress(char[] chars) 4 { 5 int anchor = 0; 6 int write = 0; 7 8 for(int read = 0; read < chars.length; read++) 9 { 10 if(read + 1 == chars.length || chars[read + 1] != chars[read]) 11 { 12 chars[write++] = chars[anchor]; 13 14 if(read > anchor) 15 { 16 String num = read - anchor + 1 + ""; 17 for(char c : num.toCharArray()) 18 chars[write++] = c; 19 } 20 21 anchor = read + 1; 22 } 23 } 24 25 return write; 26 } 27 }
参考资料:https://leetcode.com/problems/string-compression/solution/
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/