Leetcode 151 Reverse Words in a String
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue", Output: "blue is sky the".
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
這個題的意思是將一串字元倒置。
(1)我的方法是直接將字串分離出來再進行重新的拼接
public class Solution {
public String reverseWords(String s) {
String[] ss = s.trim().split("\\s+");//trim().split("\\s+")
String a = "";
for(int i = ss.length - 1;i >= 1 ;--i){
a += ss[i] + " ";
}
return a + ss[0];
}
}
(2)最佳的是在O(1)的空間複雜度下完成的
public class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
int index = s.length() - 1;
while (index >= 0) {
if (s.charAt(index) == ' ') {
index--;
continue;
}
int start = s.lastIndexOf(' ', index) + 1;
sb.append(' ');
sb.append(s.substring(start, index + 1));//將空格兩邊的字元進行重新的拼接
index = start - 1;
}
if (sb.length() > 0) sb.deleteCharAt(0);//這一行的意思是將最前面的空格去掉
return sb.toString();//轉化為String
}
}
相關文章
- LeetCode151:Reverse Words in a StringLeetCode
- Leetcode Reverse Words in a StringLeetCode
- leetcode Reverse Words in a StringLeetCode
- LeetCode-Reverse Words in a StringLeetCode
- Reverse Words in a String leetcode javaLeetCodeJava
- LeetCode-Reverse Words in a String IILeetCode
- leetcode 344. Reverse StringLeetCode
- LeetCode-Reverse Vowels of a StringLeetCode
- 344. Reverse String--LeetCode RecordLeetCode
- [LeetCode-Easy]344. Reverse String-逆置字串LeetCode字串
- js String新增 reverse()方法JS
- leetcode Reverse IntegerLeetCode
- [CareerCup] 1.2 Reverse String 翻轉字串字串
- Leetcode 273 Integer to English WordsLeetCode
- LeetCode-Integer to English WordsLeetCode
- Leetcode 7 Reverse IntegerLeetCode
- LeetCode-Reverse BitsLeetCode
- Reverse Integer leetcode javaLeetCodeJava
- Leetcode-Problem:Reverse IntegerLeetCode
- Leetcode Evaluate Reverse Polish NotationLeetCode
- leetcode刷題--Reverse BitsLeetCode
- leetcode151: symmetric treeLeetCode
- LeetCode 第 7 題(Reverse Integer)LeetCode
- Leetcode Reverse Nodes in k-GroupLeetCode
- Leetcode Reverse Linked List IILeetCode
- Evaluate Reverse Polish Notation leetcode javaLeetCodeJava
- LeetCode之Unique Morse Code Words(Kotlin)LeetCodeKotlin
- Leetcode Substring with Concatenation of All WordsLeetCode
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- LeetCode 第 190 題 (Reverse Bits)LeetCode
- Leetcode-Reverse Linked List IILeetCode
- Leetcode-Reverse Nodes in k-GroupLeetCode
- [LeetCode] Reverse Integer 翻轉整數LeetCode
- leetcode刷題--Reverse Linked ListLeetCode
- Reverse Linked List II leetcode javaLeetCodeJava
- Reverse Nodes in k-Group leetcode javaLeetCodeJava
- Reverse a String-freecodecamp演算法題目演算法
- Leetcode 30 Substring with Concatenation of All WordsLeetCode