Java 刷题(二)

Codewars 刷题第二天,仍为字符串问题

    

第二期题目

Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.

Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Polycarpus inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.

For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".

Recently, Jonny has heard Polycarpus's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Polycarpus remixed. Help Jonny restore the original song.

Input

The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters

Output

Return the words of the initial song that Polycarpus used to make a dubsteb remix. Separate the words with a space.

Examples

songDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")  // =>  WE ARE THE CHAMPIONS MY FRIEND


题目要

            对长度不超过200的字符串进行某一子串的处理,意味着将字符串中的WUB字串去掉,恢复字符串原有的形式;

解析:    

    1.  子串意味着连续的三个字符,可以遍历,判断子串是否出现,并处理;

    2.   也可以直接用串匹配的方法进行处理!

 

答案(一):(已AC)

public static String SongDecoder (String song){

    //     Your code is here...

    return song.replaceAll("(WUB)+", "  ").trim();

    }

}

答案(二):已AC

public static String SongDecoder (String song){

if (song.length() > 200 || song.isEmpty()) {

return "";

}

char[] songCharArr = song.toCharArray();

StringBuilder strBuilder = new StringBuilder();

boolean buildingWord = false; 

int i = 0;

while (i < song.length())  {

if ((i < song.length()-2) && songCharArr[i] == 'W' && songCharArr[i+1] == 'U' && songCharArr[i+2] == 'B'){

if (buildingWord){

strBuilder.append(" ");

buildingWord = false;

}

i += 3;

} else {

strBuilder.append(songCharArr[i]);

buildingWord = true;

i += 1;

}

}

return strBuilder.toString().trim();

}

答案一:正则表达式使用直接替换掉(WUB)+ 在trim()掉首尾的空格;

答案二:通常的思路分析串的长度,以及WUB所在的位置是否为串头,串尾,去掉之后是否为可输出的内容(是否加空格);

 

 


你可能感兴趣的:(Java)