JAva:アルゴリズム-圧縮文字はaaabbcaaを入力し、a 3 b 2 ca 2を出力する方法
18578 ワード
/*
* ,
* “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);
}
}
}