提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目
1、打破驼峰命名
Complete the solution so that the function will break up camel casing, using a space between words.
Example
“camelCasing” => “camel Casing”
“identifier” => “identifier”
“” => “”
我的方案:
class Solution {
public static String camelCase(String input) {
String str = "";
int j = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i)>=65 && input.charAt(i)<=90){
str +=input.substring(j,i)+" ";
j=i;
}else if (i ==input.length()-1){
str += input.substring(j);
}
}
return str;
}
}
别人的解题方案:
import java.util.Arrays;
class Solution {
public static String camelCase(String input) {
return input.replaceAll("([A-Z])", " $1");
}
别人的解题方案优雅简洁,使用正则表达式,替换掉所有的大写字母,加空格,就达到题目要求,我的解题方法比较蛮干,自己有点思维固定,需要改善。
2、解码摩尔斯电码
在这个套路中,您必须编写一个简单的摩尔斯电码解码器。虽然摩尔斯电码现在主要被语音和数字数据通信渠道所取代,但它仍在世界各地的某些应用中使用。
摩尔斯电码将每个字符编码为“点”和“破折号”的序列。例如,字母A编码为·−,字母Q编码为−−·−,数字1编码为·−−−−。摩尔斯电码不区分大小写,传统上使用大写字母。当消息以摩尔斯电码书写时,一个空格用于分隔字符代码,三个空格用于分隔单词。例如,HEY JUDE摩尔斯电码中的消息是···· · −·−− ·−−− ··− −·· ·。
注意:代码前后的额外空格没有意义,应忽略。
除了字母、数字和一些标点符号外,还有一些特殊的服务代码,其中最臭名昭著的是国际求救信号SOS(最早由泰坦尼克号发出),编码为···−−−···。这些特殊代码被视为单个特殊字符,通常作为单独的字进行传输。
您的任务是实现一个将莫尔斯电码作为输入并返回经过解码的人类可读字符串的函数。
例如:
MorseCodeDecoder.decode(“… . -.-- .— …- -… .”)
//should return “HEY JUDE”
注意:出于编码目的,您必须使用 ASCII 字符.和-,而不是 Unicode 字符。
我的解题:
public class MorseCodeDecoder {
public static String decode(String morseCode) {
// your brilliant code here, remember that you can access the preloaded Morse code table through MorseCode.get(code)
String[] words = morseCode.trim().split(" {3}");
String str = "";
for (String s :words) {
for (String s1 :s.split(" ")) {
str += MorseCode.get(s1);
}
str += " ";
}
return str.trim();
}
}
别人的解题:
public class MorseCodeDecoder {
public static String decode(String morseCode) {
return stream(morseCode.trim().split(" "))
.map(word -> stream(word.split(" ")).map(MorseCode::get).collect(joining()))
.collect(joining(" "));
}
}
我使用两个foreach循环将字符串拼接,但是没有想到使用stream流进行遍历,在使用joining进行拼接
总结
开工第一天,少少刷两道题目,找下感觉,虽然自己题目做出来了,但是和大佬们比较还是差距很明显的,需要优化代码,整顿思维,使自己的代码更优雅简洁。