问题:
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"。
解决:
① 使用StringBuilder执行,实现非常方便,但是耗时长。
public class Solution {//20ms
public String reverseWords(String s) { if(s == null) return null; StringBuilder sb = new StringBuilder(); String[] schar = s.split(" "); for (String sc : schar) { for (int i = sc.length() - 1;i >= 0 ;i -- ) { sb.append(sc.charAt(i)); } sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } }进化版:
public class Solution {//14 ms
public String reverseWords(String s) { String[] words = s.split(" "); StringBuilder sb = new StringBuilder(); boolean isFirst = true; for(String word : words){ StringBuilder temp = new StringBuilder(word); word = temp.reverse().toString(); if(isFirst){ sb.append(word); isFirst = false; }else{ sb.append(" " + word); } } return sb.toString(); } }② 全部用数组实现:
public class Solution {//6ms
public String reverseWords(String s) { char[] schar = s.toCharArray(); int start = 0; int end; while((end = s.indexOf(' ',start)) != -1){ reverse(schar,start,end - 1); start = end + 1; } reverse(schar,start,schar.length - 1); return new String(schar); } public void reverse(char[] arr,int start,int end){ while(start <= end){ char tmp = arr[start]; arr[start] = arr[end]; arr[end] = tmp; start ++; end --; } } }