有道算法题是“单词反转”,闲着没事就撸一把,动动脑~
此题有两种理解:1. 将输入字符串按字符反转输出。2. 将句子以单词为最小单位(空格区分)反转输出。
举个栗子,直观点。
输入字符串: i am a coder.
理解1,输出:.redoc a ma i
理解2,输出:.coder a am i
直接贴代码吧
// 题目: 单词反转
public static void main(String[] args) {
// 字符反转思路:1. 反向遍历输出 2. 利用对称性遍历一半。
// 反转句子但不反转其中单词思路:首先剔除前后多余空格,然后反转整个句子,最后遍历反转每个单词。
String str = "abcdef";
String sen = " i am a student dfdkfj";
ReverseWord reverseWord = new ReverseWord();
String ret = reverseWord.reverseTwo(str);
System.out.println(ret);
System.out.println(reverseWord.reverseSentence(sen));
}
/**
* 字符反转方式1
*
* @param originStr
* @return
*/
private String reverseOne(String originStr) {
if (originStr == null || originStr.isEmpty()) {
return originStr;
}
final int length = originStr.length();
StringBuilder sBuilder = new StringBuilder(length);
for (int i = length - 1; i >= 0; i--) {
sBuilder.append(originStr.charAt(i));
}
return sBuilder.toString();
}
/**
* 字符反转方式1
*
* @param originStr
* @return
*/
private String reverseTwo(String originStr) {
if (originStr == null || originStr.isEmpty()) {
return originStr;
}
final int length = originStr.length();
char[] chars = originStr.toCharArray();
final int halfLen = length / 2;
for (int i = 0; i < halfLen; i++) {
char temp = chars[i];
chars[i] = chars[length - 1 - i];
chars[length - 1 - i] = temp;
}
return new String(chars);
}
/**
* 反转句子
* @param sentence
* @return
*/
private String reverseSentence(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return sentence;
}
sentence = sentence.trim();
String[] strings = sentence.split(" ");
int halfLen = strings.length / 2;
for (int i = 0; i < halfLen; i++) {
String temp = strings[i];
strings[i] = strings[strings.length - 1 - i];
strings[strings.length - 1 - i] = temp;
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
stringBuilder.append(strings[i]);
stringBuilder.append(" ");
}
return stringBuilder.toString();
}
写完了,思路在注释里。但总觉得实现有待优化,特别是反转句子的实现,感觉使用了sentence.split(" "),正则匹配较耗时,有好的解题思路还请指教,欢迎浏览交流~