首页 > 代码库 > [LeetCode]151 Reverse Words in a String
[LeetCode]151 Reverse Words in a String
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。