【LeetCode在线编程记录-1】字符串按单词反转
来源:互联网 发布:触摸屏编程软件下载 编辑:程序博客网 时间:2024/05/17 02:13
写在前面
LeetCode(地址:https://oj.leetcode.com/)是一个在线编程网站,题目经典,测试用例完备,共计157道算法类的题目。之后我会记录我的一些练习题目,有些答案是我自己原创的(说是原创,也很可能是之前在别的地方看到的而已),有些是从讨论区看到的,我都会明确标注出处。
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.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
【我的分析】原来希望通过字符串全部反转然后按单词进行反转即可,但是遇到的困难是多个空格如何处理的问题。
【分析1-非原创】需要考虑的情况是单词与单词之间可能是多个空格。从前往后扫描得到字符temp,最后返回的是字符串result:
1)如果不是空格,word+=temp;
2)如果是空格,将word附加到result前面。
参考:https://oj.leetcode.com/discuss/10888/my-java-solution-few-lines
/* 方法1:二级缓存的思想,word来存储字符,遇到空格,如果word不是空格,将word添加到字符串的newStr前面,同时置为"" */ public static String reverseWords4(String s) { String temp = ""; String result = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ' ') { if (temp != "" && result != "") { result = temp + " " + result; } if (temp != "" && result == "") { result = temp; } temp = ""; } else { temp += c; } } /* 最后一次添加 */ if (temp != "" && result != "") { result = temp + " " + result; } if (temp != "" && result == "") { result = temp; } return result; }
【分析2-非原创】利用正则表达式将字符串分隔成字符串数组。这要用到系统函数。
参考:https://oj.leetcode.com/discuss/9142/my-accepted-java-solution
方案一:系统函数trim()和split()
/* 正则表达\s+表示任意多个空白字符 */ public static String reverseWords3(String s) { String[] parts = s.trim().split("\\s+"); String out = ""; if (parts.length > 0) { for (int i = parts.length - 1; i > 0; i--) { out += parts[i] + " "; } out += parts[0]; } return out; }
方案二:系统类Scanner默认构造函数会将字符串按空白字符分隔
public String reverseWords(String s) { Scanner parts = new Scanner(s); String result = ""; while(parts.hasNext()){ result = parts.next() + " " + result; } return result.trim(); }
- 【LeetCode在线编程记录-1】字符串按单词反转
- LeetCode按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- 按单词反转字符串
- leetcode之反转给定字符串中的单词
- 字符串反转,单词反转
- Easy:字符串按单词反转
- 【字符串1】反转单词顺序
- 笔试题-反转字符串和按单词反转字符串
- 面试问题之 按单词反转字符串
- 面试问题之 按单词反转字符串
- 简单面试题::字符串按单词反转
- Python字符串处理:按单词反转
- 字符串单词顺序反转
- 总结2
- Android开发之ViewPager实现轮播图(轮播广告)效果的自定义View
- java规则引擎你应该知道的几点东西
- 采用CAS原理构建单点登录
- Xml的操作
- 【LeetCode在线编程记录-1】字符串按单词反转
- 计算机专业词汇、词组、缩写,普通含义、专业含义,详细解释。(个人总结,不断更新)
- JQGrid 多级 Header Group 问题
- 关于SPSS软件的使用
- 代理模式(Proxy)
- JavaScript _note
- Java:eclipse下开发webservice教程
- 项目产品化升级数据库脚本问题——如何查询两个数据库差异的库表或者数据
- oracle日期格式操作