当前位置:网站首页>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();}} 边栏推荐
猜你喜欢

Mysql transaction isolation level and MVCC (multi-version concurrency control)

【Acunetix-Forgot your password】

看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!

QAbstractScrollArea、QScrollArea

【Acunetix-忘记密码】

CCF论文会议 IEEE 如何查询某个会议期刊的所有文章

云原生(三十) | Kubernetes篇之应用商店-Helm介绍

10份重磅报告 — 展望中国数字经济未来

Crack detection technology based on deep learning

面积曲线AUC(area under curve)
随机推荐
Hub and Spoke配置案例
Swift中什么时候不能用 () 代替 Void 来使用
如何在 UE4 中制作一扇自动开启的大门
CCF paper conference IEEE how to query all articles of a conference journal
[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover
云原生(三十) | Kubernetes篇之应用商店-Helm介绍
学习经验分享之七:YOLOv5代码中文注释
Multithreading (Basic) - 40,000 word summary
The exchange - string dp
JSP中include指令的功能简介说明
Oracle 19c配置ob server
打破千篇一律,DIY属于自己独一无二的商城
sva 断言资料
npm run serve启动报错npm ERR Missing script “serve“
QT笔记——QT类反射机制简单学习
SQLAlchemy使用教程
Coroutines and Lifecycle in Kotlin
SQL function TRIM
服务器间传输文件
npm install报错npm ERR Could not resolve dependency npm ERR peer