剑指offer-翻转单词顺序列
2018-03-31 21:40
411 查看
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?地址: 牛客链接
问题分析
首先,可以用java处理字符串的那几个 API 做,但会使用额外空间,也并不是面试官想要的答案注意边界条件
推荐方法:先对该字符数组整体反转,然后对该字符串中的单词进行反转
难点:如何在遍历过程中确定一个单词,具体见代码
经验教训
推荐方法代码实现
用API做public String ReverseSentence1(String str) { //注意trim() if (str == null || str.length() == 0 || str.trim().equals("")) { return str; } String[] strs = str.split(" "); StringBuffer sb= new StringBuffer(); int i = strs.length - 1; while (i > 0) { sb.append(strs[i]).append(" "); i--; } //注意最后是没有空格的 return sb.append(strs[i]).toString(); }
推荐做法
public String ReverseSentence(String str) { if (str == null) { return str; } char[] chs = str.toCharArray(); //先整体反转 reverse(chs, 0, chs.length - 1); int begin = 0; int end = 0; for (int i = 0; i < chs.length; i++) { //确定一个单词的begin 与 end if(chs[i] != ' ') { //确定begin begin = i; while (i < chs.length && chs[i] != ' ') { //确定end end = i++; } //反转该单词 reverse(chs, begin, end); i--; } //确定单词的另一种方法 /* if ( (i - 1 >= 0 && chs[i - 1] == ' ' && chs[i] != ' ' )|| (i == 0 && chs[i] != ' ')) { begin = i; } if ((i + 1 < chs.length && chs[i + 1] == ' ' && chs[i] != ' ') || (i == chs.length - 1 && chs[i] != ' ')) { end = i; reverse(chs, begin, end); } */ } return new String(chs); } //反转chs[]的 begin~end部分 public void reverse(char[] chs, int begin, int end) { int i = begin; int j = end; while (i < j) { char temp = chs[i]; chs[i] = chs[j]; chs[j] = temp; i++; j--; } }
相关文章推荐
- 《剑指offer》翻转单词顺序列
- 《剑指offer》翻转单词顺序列
- 剑指offer—翻转单词顺序列
- 《剑指offer》-翻转单词顺序列
- 剑指offer 42题 【知识迁移能力】翻转单词顺序列
- 剑指offer——面试题42:翻转单词序列
- 剑指Offer(58)翻转单词顺序列(题目二)
- 剑指offer--面试题42: 翻转单词顺序列 vs 左旋转字符串
- 剑指offer--翻转单词顺序列
- 剑指offer系列之42:翻转单词序列
- 剑指Offer: 翻转单词顺序列、左旋转字符串
- 剑指offer(四十一)之翻转单词顺序列
- 剑指Offer——翻转单词顺序列
- 《剑指offer》刷题笔记(知识迁移能力):翻转单词顺序列
- 翻转单词顺序列(剑指offer) 反转字符串的应用
- 剑指offer——翻转单词顺序列
- 《剑指offer》-翻转单词顺序列
- 牛客:剑指offer:翻转单词顺序列 (Java)
- 剑指offer(41)-翻转单词顺序列
- 剑指offer刷题之c、c++实现的翻转单词顺序列