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: "Let"s take LeetCode contest"
Output: "s"teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
class Solution { public String reverseWords(String s) { if (s == null || s.length() == 0) return s; String[] strs = s.split(" "); StringBuilder sb = new StringBuilder(); for (String str: strs) { str = reverse(str); sb.append(str).append(" "); } return sb.toString().trim(); } private String reverse(String str) { StringBuilder sb = new StringBuilder(); for (int i = str.length()-1; i >= 0; i--) { sb.append(str.charAt(i)); } return sb.toString(); } }StringBuilder for everything
class Solution { public String reverseWords(String s) { String[] strs = s.split(" "); StringBuilder sb = new StringBuilder(); for (String str: strs) { str = new StringBuilder(str).reverse().toString(); sb.append(str+" "); } return sb.toString().trim(); } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/71917.html
摘要:公眾號(hào)愛(ài)寫(xiě)給定一個(gè)字符串,你需要反轉(zhuǎn)字符串中每個(gè)單詞的字符順序,同時(shí)仍保留空格和單詞的初始順序。示例輸入輸出注意在字符串中,每個(gè)單詞由單個(gè)空格分隔,并且字符串中不會(huì)有任何額外的空格。 公眾號(hào):愛(ài)寫(xiě)bug(ID:icodebugs) 給定一個(gè)字符串,你需要反轉(zhuǎn)字符串中每個(gè)單詞的字符順序,同時(shí)仍保留空格和單詞的初始順序。 Given a string, you need to revers...
摘要:公眾號(hào)愛(ài)寫(xiě)給定一個(gè)字符串,你需要反轉(zhuǎn)字符串中每個(gè)單詞的字符順序,同時(shí)仍保留空格和單詞的初始順序。示例輸入輸出注意在字符串中,每個(gè)單詞由單個(gè)空格分隔,并且字符串中不會(huì)有任何額外的空格。 公眾號(hào):愛(ài)寫(xiě)bug(ID:icodebugs) 給定一個(gè)字符串,你需要反轉(zhuǎn)字符串中每個(gè)單詞的字符順序,同時(shí)仍保留空格和單詞的初始順序。 Given a string, you need to revers...
摘要:題目鏈接題目分析題目要求把句子中的每個(gè)單詞都倒轉(zhuǎn)過(guò)來(lái)。思路這個(gè)很簡(jiǎn)單,用空格把句子分割,再用把字符串倒轉(zhuǎn)過(guò)來(lái),拼接起來(lái)就可以了。最終代碼若覺(jué)得本文章對(duì)你有用,歡迎用愛(ài)發(fā)電資助。 557. Reverse Words in a String III 題目鏈接 557. Reverse Words in a String III 題目分析 題目要求把句子中的每個(gè)單詞都倒轉(zhuǎn)過(guò)來(lái)。 思路 這個(gè)...
摘要:一題目描述空格分隔,逐個(gè)反轉(zhuǎn)二題目描述三題目描述當(dāng)然也可以用的做,不過(guò)用雙指針更快。 LeetCode: 557. Reverse Words in a String III 一、LeetCode: 557. Reverse Words in a String III 題目描述 Given a string, you need to reverse the order of chara...
摘要:思路先用將字符串分割,再遍歷,將字符串內(nèi)每個(gè)單詞進(jìn)行翻轉(zhuǎn)代碼題意給定一個(gè)字符串,將字符串按照翻轉(zhuǎn),不翻轉(zhuǎn)的規(guī)則進(jìn)行處理。思路先將字符串分段,然后再根據(jù)段落進(jìn)行處理最后將字符串輸出。 344 Reverse String題意:給出一個(gè)字符串對(duì)字符串進(jìn)行翻轉(zhuǎn)(reverse)思路:直接使用切片函數(shù)進(jìn)行翻轉(zhuǎn)(網(wǎng)上看到的,具體怎么使用有點(diǎn)迷)[::-1]代碼:`class Solution(...
閱讀 1887·2021-10-12 10:12
閱讀 2634·2021-09-29 09:42
閱讀 2889·2021-09-03 10:28
閱讀 2318·2019-08-30 15:54
閱讀 1222·2019-08-30 15:53
閱讀 1470·2019-08-30 11:26
閱讀 3419·2019-08-30 11:02
閱讀 2203·2019-08-30 11:02