当前位置:网站首页>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();}} 边栏推荐
- JVM简介
- The sitcom "Re-Walking the Long March" was staged
- yolo格式(txt)数据集转VOC(xml)
- SQL函数 $TRANSLATE
- Problem solving in the process of using mosquitto
- Several reasons why applet plugins benefit developers
- npm install报错npm ERR Could not resolve dependency npm ERR peer
- SQL function TRIM
- 5G网络切片技术
- 借小程序容器打造自有App小程序生态
猜你喜欢
随机推荐
Shell编程之条件语句
leetcode: 200. Number of islands
[kali-information collection] (1.9) Metasploit + search engine tool Shodan
匹配滤波(四种滤波器的幅频特性)
如何在 UE4 中制作一扇自动开启的大门
网站自动翻译-网站批量自动翻译-网站免费翻译导出
DTG-SSOD:最新半监督检测框架,Dense Teacher(附论文下载)
喜迎八一 《社会企业开展应聘文职人员培训规范》团体标准出版发行会暨橄榄枝大课堂上线发布会在北京举行
SQL 经典50题(题目+解答)(1)
基于深度学习的裂缝检测技术
Several reasons why applet plugins benefit developers
Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
项目监控六大事项
Crack detection technology based on deep learning
QListView的使用
X86函数调用模型分析
智能手表前景如何?
SQL函数 $TRANSLATE
5G网络切片技术
故障分析 | 一条 SELECT 语句跑崩了 MySQL ,怎么回事?









