"Leetcode Brush problem Java Edition" Reverse Words in a String

Source: Internet
Author: User

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?
      reduce them to a single space in the reversed string.
Package com.liuhao.acm.leetcode;/** * @author Liuhao *  *         Given A input string, reverse the string word by word. F  or example, *         Given s = "The Sky is Blue", return "Blue was Sky the". */public class Reversewords {public static String Reversewords (string s) {//If the input string is directly empty, return the string if (S.equals (")) {return" ";} Divide the string by the space "\\s{1,}" and the regular of one or more spaces: "\\s{1,}" string[] Strarr = S.split ("\\s{1,}"); int len = strarr.length;// After splitting the string into an empty string, return directly if (len = = 0) {return "";} Use StringBuilder more effective StringBuilder sb = new StringBuilder ("");//invert the output before splitting the string array for (int i = len-1; I >= 0; i--) {if (!strarr[i].equals (")") {Sb.append (strarr[i]); Sb.append ("");}} Sb.deletecharat (Sb.lastindexof ("")); return sb.tostring ();} public static void Main (string[] args) {System.out.println (Reversewords (""));}}

"Leetcode Brush problem Java Edition" Reverse Words in a String

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.