1. 程式人生 > >java演算法題 - 1 如何輸入aaabbcaa,輸出a3b2ca2

java演算法題 - 1 如何輸入aaabbcaa,輸出a3b2ca2

/*
 *  寫一個函式把連續字串壓縮,無需考慮編碼
 *  輸入“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);
    }
  }
}