Amazon
  • Introduction
  • Phone Interview I
    • 53.Reverse Words in a String
    • 31.Partition Array
  • Phone Interview II
    • 167.Add Two Numbers
    • 88.Lowest Common Ancestor
  • Onsite I
    • 655.Big Integer Addition
    • 221.Add Two Numbers II
  • Onsite II
    • 158.Two Strings Are Anagrams
    • 171.Anagrams
    • 386.Longest Substring with At Most K Distinct Characters
  • Onsite III
    • 479.Second Max of Array
    • 589.Connecting Graph
  • Onsite IV
    • 532.Reverse Pairs
  • 2022
    • OA
      • work simulation
      • Greyness
      • NearestRetailer
      • Sum of Scores of Subarray
      • StrengthOfPassword
      • ProductOf1
      • Move 0/1 InArray
      • Max deviation among all substrings
      • AWS power consumption
      • searchWordResultWord
      • maxOperationOfString
      • MinHealthGame
      • EarliestMonth
      • Package ship
      • RatingConsectiveDecresing
      • LinkedListSum
      • MovingBoxes
      • ValidString
      • MaxValueAfterRemovingFromString
      • Subtree with Maximum Average
    • VO
      • 2022.3
    • BQ
      • doc
      • 2022.4
      • Freq Question
      • 11大类BQ和Follow-ups
      • Page 1
      • BQ 100
      • 35 behavioral questions asked in 95% of Amazon interviews with examples
      • Page 2
      • 反向BQ
    • LP
      • LP-1
      • LP-2
    • SD
      • Design Amazon Prime Video Recommendation System
      • Amazon Order system
    • OOD
      • Linux Find Command
      • Amazon Locker
    • AWS Identity call
    • Interviews
Powered by GitBook
On this page
  • 1.Description(Easy)
  • 2.Code

Was this helpful?

  1. Phone Interview I

53.Reverse Words in a String

1.Description(Easy)

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

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

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.

2.Code

用split函数将string分成一个一个单词,在从后往前一次append到stringbuilder中,注意最后检查下是否remove last space,但是test中不加这个检查也能pass。

public String reverseWords(String s){
        if(s==null || s.length()==0){
            return "";
        }
        StringBuilder result=new StringBuilder();
        String[] str=s.split(" ");
        for(int i=str.length-1;i>=0;i--){
            if(!str[i].equals("")){
                result.append(str[i]).append(" ");
            }
        }
        //remove the last " "
        if(result.length()==0){
            return "";
        }else{
            return result.toString();
        }

    }
PreviousIntroductionNext31.Partition Array

Last updated 5 years ago

Was this helpful?