题目:https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
思路
先分割字符串-- 反转每一个Word-- 拼接起来。
我的代码 149ms
public static String reword(String s){
int i=0;
int j=s.length()-1;
char[] cs = s.toCharArray();
char temp;
while(i<j){
temp = cs[i];
cs[i] = cs[j];
cs[j] = temp;
i++;
j--;
}
return String.valueOf(cs);
}
public String reverseWords(String s) {
String res = "";
String[] arr = s.split(" ");
for(int i=0; i<arr.length; i++){
res = res + reword(arr[i])+" ";
}
return res.substring(0, res.length()-1);
}
【学习他人】
思路一样
代码 17ms
public String reverseWord(String s){
String[] strings = s.split(" ");
StringBuilder stringBuilder = new StringBuilder();
StringBuffer stringBuffer ;
for (int i = 0; i < strings.length; i++) {
stringBuffer = new StringBuffer(strings[i]);
stringBuilder.append(stringBuffer.reverse().toString() + " ");
}
return stringBuilder.toString().substring(0, stringBuilder.length() - 1);
}
【总结】
String、StringBuffer、StringBuilder的使用:
String 是字符串常量
StringBuffer 字符串变量(线程安全)
StringBuilder 字符串变量(非线程安全)
String类是不可变类,任何对String的改变都 会引发新的String对象的生成;StringBuffer则是可变类,任何对它所指代的字符串的改变都不会产生新的对象。
HashTable是线程安全的,很多方法都是synchronized方法,而HashMap不是线程安全的,但其在单线程程序中的性能比HashTable要高。StringBuffer和StringBuilder类的区别也是如此,他们的原理和操作基本相同,区别在于StringBufferd支持并发操作,线性安全的,适 合多线程中使用。StringBuilder不支持并发操作,线性不安全的,不适合多线程中使用。新引入的StringBuilder类不是线程安全的,但其在单线程中的性能比StringBuffer高。
如果我们的程序是在单线程下运行,或者是
不必考虑到线程同步问题,我们应该优先使用StringBuilder类
;如果要
保证线程安全,自然是StringBuffer
。
参考文章: