当前位置:网站首页>Leek 151 - Reverse words in a string

Leek 151 - Reverse words in a string

2022-08-02 11:45:00 Zhang Ran Ran √

Title description

Given a string s , reverse the order of the words in the string.

word is a string of non-whitespace characters.Separate the words in the string with at least one space in s.

Returns the resulting string of words in reverse order and concatenated with a single space between words.

Note: The input string s may contain leading spaces, trailing spaces, or multiple spaces between words.In the returned result string, words should be separated by only a single space and not contain any extra spaces.

Solution ideas

  • This question mainly examines the knowledge of StringBuffer and Deque, and creates a StringBuffer str and Deque deque;
  • Put the original string into the String array separated by spaces;
  • Using the deque stack, push the elements in the String onto the stack;
  • Append the elements in the stack to str;
  • Convert str to String.

Input and output example

Code

class Solution {public String reverseWords(String s) {String[] stringArray = s.split(" ");StringBuffer str = new StringBuffer();int len ​​= stringArray.length;Deque deque = new LinkedList<>();for(String i : stringArray){if(!"".equals(i)) deque.addFirst(i);}while(!deque.isEmpty()){str.append(deque.pop()).append(" ");}if(str.length() != 0){str.deleteCharAt(str.length()-1);}return str.toString();}}

原网站

版权声明
本文为[Zhang Ran Ran √]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208021141359815.html