首页 > 代码库 > 【LeetCode在线编程记录-1】字符串按单词反转
【LeetCode在线编程记录-1】字符串按单词反转
写在前面
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】字符串按单词反转