/*
* 写一个函数把连续字符串压缩,无需考虑编码
* 输入“aaabbcaa” 输出“a3b2ca2”
* 输入“a” 输出“a”
*/
public class ZipLetters{
public static void main(String args[]){
zipLetters("aaabbcaa");
zipLetters("ccaabaadef");
zipLetters("");
zipLetters("f");
}
public static void zipLetters(String str){
if (str==null|str==""){
System.out.println("");
}
else if (str.length()==1){
System.out.println(str);
}
else{
//instantiate an stringbuffer to store the compressed letters
StringBuffer outputStr = new StringBuffer();
//instantiate a counter to count the number of same letters
//in a roll before encounter a different one
int counter = 1;
for (int cursor=0; cursor<str.length(); cursor++){
//check if the the cursor is pointing to the last letter
if (cursor+1 == str.length()){
if (str.charAt(cursor-1)==str.charAt(cursor)){
outputStr.append(str.charAt(cursor));
outputStr.append(counter);
}
else{
outputStr.append(str.charAt(cursor));
}
}
//then it means we could check next letter for a pair
else{
//if the referencing char is not equal to the next letter
//then append this letter to the output Stringbuffer
if(str.charAt(cursor)!=str.charAt(cursor+1)){
outputStr.append(str.charAt(cursor));
//dont show the count if it shows up only once
if (counter>1){
outputStr.append(counter);
}
//reset the counter
counter = 1;
}
//then we find a pair of same letters
//count once for this letter
else{
counter++;
}
}
}
//the base else block ends here
System.out.println(outputStr);
}
}
}
if (counter>1){
outputStr.append(counter);
}
可以写成
outputStr.append(counter==1 ? "" : counter);
上面方法是从字符串下标0遍历,利用当前字符比较下一个字符寻找配对字符
如果我们定义一个参数findPair来表示要找配对的字符,从字符串下标1开始遍历,则代码写成
/*
* 写一个函数把连续字符串压缩,无需考虑编码
* 输入“aaabbcaa” 输出“a3b2ca2”
* 输入“a” 输出“a”
*/
public class ZipLettersBeta{
public static void main(String args[]){
zipLetters("aaabbcaa");
zipLetters("ccaabaadef");
zipLetters("");
}
public static void zipLetters(String str){
if (str==null|str==""){
System.out.println("");
}
else if (str.length()==1){
System.out.println(str);
}
else{
StringBuffer outputStr = new StringBuffer();
int counter = 1;
char findPair = str.charAt(0);
for (int i = 1; i<str.length(); i++){
if (findPair == str.charAt(i)){
counter++;
}
else{
outputStr.append(findPair);
outputStr.append(counter==1?"" : counter);
counter = 1;
findPair = str.charAt(i);
}
}
outputStr.append(findPair);
outputStr.append(counter==1?"" : counter);
System.out.println(outputStr);
}
}
}