标签:leetcode
https://oj.leetcode.com/problems/reverse-words-in-a-string/
http://blog.csdn.net/linhuanmars/article/details/20982463
public class Solution { public String reverseWords(String s) { // Solution A: return reverseWords_Char(s); // Solution B: // return reverseWords_Split(s); } ///////////////////// // Solution A: Char // public String reverseWords_Char(String s) { if (s == null) return null; char[] chars = s.toCharArray(); int len = chars.length; StringBuilder sb = new StringBuilder(); StringBuilder subsb = new StringBuilder(); for (int i = 0 ; i < len ; i ++) { char c = chars[i]; if (c == ‘ ‘) { if (subsb.length() > 0) { if (sb.length() == 0) sb.append(subsb.toString()); else sb.insert(0, subsb.toString() + " "); subsb = new StringBuilder(); } } else subsb.append(c); } if (subsb.length() > 0) { if (sb.length() == 0) sb.append(subsb.toString()); else sb.insert(0, subsb.toString() + " "); } return sb.toString().trim(); } ///////////////////// // Solution B: split // public String reverseWords_Split(String s) { if (s == null) return null; s = s.trim(); if (s.isEmpty()) return ""; String[] strs = s.split(" "); StringBuilder sb = new StringBuilder(); for (int i = strs.length - 1 ; i >= 0 ; i --) { sb.append(strs[i]).append(" "); } return sb.toString().trim(); } }
[LeetCode]151 Reverse Words in a String
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1601169