当前位置:网站首页>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();}} 边栏推荐
- Create an application operation process using the kubesphere GUI
- 21 Days Learning Challenge - Day 1 Punch (Screen Density)
- 力扣209-长度最小的字符串——滑动窗口法
- 【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
- Hub and Spoke配置案例
- 小程序插件让开发者受益的几个理由
- LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一
- MP的几种查询方式
- LeetCode笔记:Weekly Contest 304
- 借小程序容器打造自有App小程序生态
猜你喜欢

Hub and Spoke配置案例

Swift中什么时候不能用 () 代替 Void 来使用

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

Mysql事务隔离级别与MVCC(多版本并发控制)

CCF paper conference IEEE how to query all articles of a conference journal

细学常用类,集合类,IO流

使用kubesphere图形界面创建一个devops的CI/CD流程

基于threejs的商品VR展示平台的设计与实现思路

When not to use () instead of Void in Swift

图形处理单元(GPU)的演进
随机推荐
ASP.NET Core 6框架揭秘实例演示[31]:路由&ldquo;高阶&rdquo;用法
leetcode: 200. Number of islands
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
Running yum reports Error: Cannot retrieve metalink for reposit
pyqt5连接MYSQL数据库问题
受邀出席Rust开发者大会|Rust如何助力量化高频交易?
翻译英语的软件-免费翻译软件-各种语言互相翻译
如何在 UE4 中制作一扇自动开启的大门
华为eNSP(基础实验通信)
darknet训练yolov4模型
Idea 全局搜索(idea如何全局搜索关键字)
LeetCode笔记:Weekly Contest 304
您应该知道的 Google Sheets 使用技巧
Excel动态图制作
MapStruct
匹配滤波(四种滤波器的幅频特性)
npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
中原银行实时风控体系建设实践
阿苹的思考
Jest 测试框架 beforeEach 的设计原理解析