LeetCode:557. Reverse Words in a String III(反轉每個單詞)
阿新 • • 發佈:2018-12-26
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.
方法1:(這種比較直接的做法,可能效率會有點低)
class Solution { public String reverseWords(String s) { StringBuffer sb=new StringBuffer(s); StringBuffer newSb=new StringBuffer(); String [] strs=sb.reverse().toString().split(" +"); for(int i=strs.length-1;i>=0;i--){ newSb.append(strs[i]+" "); } return newSb.toString().trim(); } }
時間複雜度:O(n)
空間複雜度:O(n)
方法2:(在方法1的基礎上有一些改進,不過還是利用方法的原理進行計算)
package leetcode; import org.junit.Test; /** * @author zhangyu * @version V1.0 * @ClassName: ReverseWords * @Description: TOTO * @date 2018/11/30 14:30 **/ public class ReverseWords { @Test public void fun() { String s = "we are from china"; String newString = reverseString(s); System.out.println(newString); } private String reverseString(String s) { String[] strs = s.split(" +"); StringBuilder sb = new StringBuilder(); for (String ss : strs) { sb.append(new StringBuilder(ss).reverse()+" "); } return sb.toString().trim(); } }
時間複雜度:O(n)
空間複雜度:O(n)