摘要:思路把以空格為間隔分隔開存入然后倒著加入并且每個(gè)加入以后后面加空格,最后記的清除最后一個(gè)空格。
Reverse Words in a String
Given an input string, reverse the string word by word.
For example, Given s = "the sky is blue", return "blue is sky the".
思路: 把string以空格為間隔分隔開存入array, 然后倒著加入stringBuilder并且每個(gè)加入以后后面加空格,最后記的清除最后一個(gè)空格。
public class Solution { public String reverseWords(String s) { if (s == null || s.length() == 0) { return ""; } String[] array = s.split(" "); StringBuilder sb = new StringBuilder(); for (int i = array.length - 1; i >= 0; i--) { if (!array[i].equals("")) { sb.append(array[i]).append(" "); } } //remove the last " " return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1); } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/64797.html
摘要:代碼先反轉(zhuǎn)整個(gè)數(shù)組反轉(zhuǎn)每個(gè)單詞雙指針交換法復(fù)雜度時(shí)間空間思路這題就是版的做法了,先反轉(zhuǎn)整個(gè)數(shù)組,再對每個(gè)詞反轉(zhuǎn)。 Reverse Words in a String Given an input string, reverse the string word by word. For example, Given s = the sky is blue, return blue is...
Problem Reverse Words in a String IIGiven an input string , reverse the string word by word. Example Input: [t,h,e, ,s,k,y, ,i,s, ,b,l,u,e]Output: [b,l,u,e, ,i,s, ,s,k,y, ,t,h,e] Note A word is defin...
Problem 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: Lets take LeetCode contest...
摘要:題目鏈接題目分析題目要求把句子中的每個(gè)單詞都倒轉(zhuǎn)過來。思路這個(gè)很簡單,用空格把句子分割,再用把字符串倒轉(zhuǎn)過來,拼接起來就可以了。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 557. Reverse Words in a String III 題目鏈接 557. Reverse Words in a String III 題目分析 題目要求把句子中的每個(gè)單詞都倒轉(zhuǎn)過來。 思路 這個(gè)...
摘要:題目要求講一個(gè)字符串中的單詞逆序輸出,單詞中字母順序不發(fā)生改變。其中,字符串首位的空格應(yīng)刪去,字符串中如果存在多余的空格,只需輸出一個(gè)空格。這里用到的正則表達(dá)式為也就是遇到一個(gè)或多個(gè)空白時(shí)斷句。 題目要求 Given an input string, reverse the string word by word. For example, Given s = the sky is ...
閱讀 2704·2023-04-25 17:21
閱讀 2564·2021-11-23 09:51
閱讀 2860·2021-09-24 10:32
閱讀 3785·2021-09-23 11:33
閱讀 1986·2019-08-30 15:44
閱讀 3463·2019-08-30 11:18
閱讀 3538·2019-08-30 10:53
閱讀 635·2019-08-26 13:25