字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
解法:
用双指针。
一个i 指向第一个元素,一个 j 指向第二个元素,比较 j 所指的元素是否等于 i 指向的元素,如果相等,则进行记录,且 j 往后移继续比较,当 j 所指向的元素不再相等时, 令 i = j ,开始新的元素的比较与计数。
关键:用什么来记录并连接成字符串然后输出?
答案: 用 StringBuilder,用于单线程的可变序列。
用到的方法有:
append():This method appends the string representation of the X type argument to the sequence.
char charAt(int index): This method returns the char value in this sequence at the specified index.
String toString(): This method returns a new String that contains a subsequence of characters currently contained in this character sequence.
int length(): This method returns the length (character count).
附上代码:
public String compressString(String S) {
int N = S.length();
int i = 0;
StringBuilder sb = new StringBuilder();
while (i < N) {
int j = i;
while (j < N && S.charAt(j) == S.charAt(i)) {
j++;
}
sb.append(S.charAt(i));
sb.append(j - i);
i = j;
}
String res = sb.toString();
if (res.length() < S.length()) {
return res;
} else {
return S;
}
}
作者:nettee
链接:力扣
网友评论