目录
Java StringBuffer 和 StringBuilder 类
当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。
和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。
StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)。
由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。然而在应用程序要求线程安全的情况下,则必须使用 StringBuffer 类。(或许面试会考?)
public class Test{
public static void main(String args[]){
StringBuffer sBuffer = new StringBuffer("菜鸟教程官网:");
sBuffer.append("www");
sBuffer.append(".runoob");
sBuffer.append(".com");
System.out.println(sBuffer);
}
}
输出
菜鸟教程官网:www.runoob.com
No. | Method |
---|---|
1 | public StringBuffer append(String s) 将指定的字符串追加到此字符序列。 |
2 | public StringBuffer reverse() 将此字符序列用其反转形式取代。 |
2 | public delete(int start, int end) 移除此序列的子字符串中的字符。 |
2 | public insert(int offset, int i) 将 int 参数的字符串表示形式插入此序列中。 |
2 | replace(int start, int end, String str) 使用给定 String 中的字符替换此序列的子字符串中的字符。 |
其他Methods和 String 类的方法类似:
int capacity()
, char charAt(int index)
, int length()
, void setLength(int newLeength)
, etc.
Leetcode 557. Reverse Words in a String III
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"
Sample Solution:
class Solution {
public String reverseWords(String s) {
String words[] = split(s);
StringBuilder res = new StringBuilder();
for (String word: words)
res.append(reverse(word) + " ");
return res.toString().trim();
}
public String[] split(String s){
ArrayList <String> words = new ArrayList<>();
StringBuilder word = new StringBuilder();
for (int i = 0; i < s.length(); i++){
if (s.charAt(i) == ' '){
words.add(word.toString());
word = new StringBuilder();
} else
word.append(s.charAt(i));
}
words.add(word.toString());
return words.toArray(new String[words.size()]);
}
public String reverse(String s) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < s.length(); i++){
res.insert(0, s.charAt(i));
}
return res.toString();
}
}
我自己写的Python解法真是菜到抠脚:
Python
class Solution:
def reverseWords(self, s: str) -> str:
# get the total number of words
n = 1
for i in s:
if i.isspace() == True:
n += 1
# split word
k = 0
words = [""] * n
flag = False
for chars in s:
if chars.isspace() == False:
words[k] = words[k] + chars
flag = True # for corner case
elif chars.isspace() == True:
k += 1
else:
words[k] = ""
# reverse word
res = ""
for word in words:
res += word[::-1] + " "
res = res[0:len(res)-1]
# corner case
if flag == False:
res = ""
return res
三行Python
class Solution:
def reverseWords(self, s: str) -> str:
s = s.split()
s = [x[::-1] for x in s]
return ' '.join(s)
[1] https://www.runoob.com/java/java-stringbuffer.html
[2] https://leetcode.com/problems/reverse-words-in-a-string-iii/