Leetcode 151 Reverse Words in a String
阿新 • • 發佈:2019-01-01
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 } }