CodingBat 上存在一个名为repeatSeparator的问题。
Given two strings, word and a separator sep, return a big string made of count occurrences of the word, separated by the separator string.
repeatSeparator("Word", "X", 3) ? "WordXWordXWord"
repeatSeparator("This", "And", 2) ? "ThisAndThis"
repeatSeparator("This", "And", 1) ? "This"
Run Code Online (Sandbox Code Playgroud)
我知道如何解决它,但我的解决方案和我在互联网上找到的大多数解决方案都使用循环。有没有办法在没有循环的情况下解决这个问题?
我需要的伪代码return (word+rep)*count;不起作用,但有没有办法实现类似的结果?
我非常重视任何答复。
使用 Java 11 的一个班轮:
String repeatSeparator(String word, String sep, int count) {
return (word + sep).repeat(count-1) + word;
}
Run Code Online (Sandbox Code Playgroud)
使用 Java 8 的一个班轮:
String repeatSeparator(String word, String sep, int count) {
return String.join(sep, Collections.nCopies(count, word));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
348 次 |
| 最近记录: |