leetcode-數組-151

/** * <p>給你一個字符串 <code>s</code> ,顛倒字符串中 <strong>單詞</strong> 的順序。</p> * * <p><strong>單詞</strong> 是由非空格字符組成的字符串。<code>s</code> 中使用至少一個空格將字符串中的 <strong>單詞</strong> 分隔開。</p> * * <p>返回 <strong>單詞</strong> 順序顛倒且 <strong>單詞</strong> 之間用單個空格連接的結果字符串。</p> * * <p><strong>注意:</strong>輸入字符串 <code>s</code>中可能會存在前導空格、尾隨空格或者單詞間的多個空格。返回的結果字符串中,單詞間應當僅用單個空格分隔,且不包含任何額外的空格。</p> * * <p>&nbsp;</p> * * <p><strong>示例 1:</strong></p> * * <pre> * <strong>輸入:</strong>s = "<code>the sky is blue</code>" * <strong>輸出:</strong>"<code>blue is sky the</code>" * </pre> * * <p><strong>示例 2:</strong></p> * * <pre> * <strong>輸入:</strong>s = " &nbsp;hello world &nbsp;" * <strong>輸出:</strong>"world hello" * <strong>解釋:</strong>顛倒後的字符串中不能存在前導空格和尾隨空格。 * </pre> * * <p><strong>示例 3:</strong></p> * * <pre> * <strong>輸入:</strong>s = "a good &nbsp; example" * <strong>輸出:</strong>"example good a" * <strong>解釋:</strong>如果兩個單詞間有多餘的空格,顛倒後的字符串需要將單詞間的空格減少到僅有一個。 * </pre> * * <p>&nbsp;</p> * * <p><strong>提示:</strong></p> * * <ul> * <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> * <li><code>s</code> 包含英文大小寫字母、數字和空格 <code>' '</code></li> * <li><code>s</code> 中 <strong>至少存在一個</strong> 單詞</li> * </ul> * * <ul> * </ul> * * <p>&nbsp;</p> * * <p><strong>進階:</strong>如果字符串在你使用的編程語言中是一種可變數據類型,請嘗試使用&nbsp;<code>O(1)</code> 額外空間複雜度的 <strong>原地</strong> 解法。</p> * <div><div>Related Topics</div><div><li>雙指針</li><li>字符串</li></div></div><br><div><li>👍 622</li><li>👎 0</li></div> */ //leetcode submit region begin(Prohibit modification and deletion) class Solution { public static String reverseWords(String s) { //去除倆邊空格 s = removeSpace(s); s = reverse(s, 0, s.length() - 1); //按空格分割單詞 每個都反轉 int start = 0; for (int i = 0; i <= s.length(); i++) { if (i == s.length() || s.charAt(i) == ' ') { s = reverse(s, start, i - 1); start = i + 1; } } return s; } static String removeSpace(String s) { int start = 0; int end = s.length() - 1; while (s.charAt(start) == ' ') start++; while (s.charAt(end) == ' ') end--; StringBuffer sb = new StringBuffer(); while (start <= end) { char c = s.charAt(start); if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') { sb.append(c); } start++; } return sb.toString(); } static String reverse(String s, int start, int end) { char[] nums = s.toCharArray(); char temp; while (start < end) { temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } return new String(nums); } } //leetcode submit region end(Prohibit modification and deletion)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章