当前位置:网站首页>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();}}
边栏推荐
猜你喜欢
随机推荐
sqli-labs(less-11)
npm run dev 和 npm run serve区别
ssm web page access database data error
如何通过DBeaver 连接 TDengine?
如何在 UE4 中制作一扇自动开启的大门
go源码之sync.Waitgroup
Problem solving in the process of using mosquitto
Learning Experience Sharing Seven: YOLOv5 Code Chinese Comments
10份重磅报告 — 展望中国数字经济未来
当POC遇见RPA:RPA项目顺利实施的关键
力扣209-长度最小的字符串——滑动窗口法
暑期总结3
ansible模块--yum模块
doc2vec和word2vec(zigbee简介及应用)
Create a devops CI/CD process using the kubesphere GUI
SQL 数据更新
JSP中如何正确的填写include指令中的file路径呢?
Excel dynamic chart production
企业级数据治理工作怎么开展?Datahub这样做
Camera Hal OEM模块 ---- cmr_snapshot.c