LeetCode-Reverse Words in a String
来源:互联网 发布:花洒推荐 知乎 编辑:程序博客网 时间:2024/06/06 06:56
题目:https://oj.leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
click to show clarification.
分析:两次翻转法,第一次翻转整个句子,第二次翻转每个单词。源码:Java版本
算法分析:时间复杂度O(n),空间复杂度O(1)
public class Solution { public String reverseWords(String s) { char[] str=s.trim().replaceAll("\\s+", " ").toCharArray(); reverse(str,0,str.length-1); int low=0,high=0; while(high<str.length) { if(str[high]!=' ') { high++; }else { reverse(str,low,high-1); high++; low=high; } } reverse(str,low,high-1); return String.valueOf(str); } private void reverse(char[] str,int low,int high) { while(low<high) { swap(str,low++,high--); } } private void swap(char[] str,int x,int y){ char temp=str[x]; str[x]=str[y]; str[y]=temp; }}
0 0
- Leetcode - string - Reverse Words in a String
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- Reverse Words in a String (LeetCode)
- LeetCode Reverse Words in a String Total
- LeetCode(151)Reverse Words in a String
- Reverse Words in a String -- LeetCode
- leetcode Reverse Words in a String
- LeetCode OJ:Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [Leetcode] Reverse Words in a String
- Reverse Words in a String[LeetCode]
- LeetCode OJ :Reverse Words in a String
- Leetcode: Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- javascript中奇怪的if-else if-else
- linux下MySQL 的使用
- ecshop商品详细描述页,批量上传图片功能实现
- VMware的二种数据存储形式:VMFS和NFS
- QT国际化, 运行时改变界面语言, 利用QT实现国际化应用程序
- LeetCode-Reverse Words in a String
- 二进制的科学计数法
- 黑马程序员————单例设计模式
- 虚拟机检测技术攻防
- 用java删除文件夹里的所有文件
- Linux Network Namespace
- Google系统结构图
- System.Threading.Thread.Sleep()
- Hadoop日志到底存在哪里?