程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode | Reverse Words in a String

LeetCode | Reverse Words in a String

編輯:C++入門知識

題目

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string. 分析

    正統的做法就是自己去逐個找到每個單詞,從前往後還是從後往前其實都差不多,都要翻轉:要麼是翻轉字母(從後往前)、要麼翻轉單詞(從前往後)。

    這裡給出的是用java自帶的split方法,幫助我們以“ ”進行切割,代碼看上去會比較簡潔明了。

    代碼

    public class ReverseWordsInAString {
    	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(" ");
    			}
    		}
    		return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
    	}
    }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved