Leetcode——557. Reverse Words in a String III
2018-02-25 15:42
399 查看
题目原址
https://leetcode.com/problems/reverse-words-in-a-string-iii/description/题目描述
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.Example1:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
解题思路
第一步:如果字符串的长度是1或者0,不做任何操作,直接返回该字符串第二步;定义三个变量,first,end,nextFirst,其中first指当前单词的第一个字母,end指当前单词的最后一个字母,nextFirst指当前单词的下一个单词的第一个字母
第三步:进入for循环,循环条件是直到字符串末尾,循环体:
(1) 每次循环都找到单词的第一个字母和最后一个字母,以及下一个单词的第一个字母
(2) 进入while循环,在while循环中处理每个单词的顺序。
(3) 在for循环的最后要更改first的值,将first的值变为下一个单词的第一个字母的下标。为下一次循环做准备
第四步:这一步容易忘记,之前的for循环找单词的条件都是通过单词后面是否有“ ”空格,但是最后一个单词后面没有空格,所以往往容易忽略对最后一个单词的处理,因此在for循环体结束后,还要对最后一个单词单独处理。
第五步:返回值是一个String字符串类型,因此new String(字符数组名),通过字符串带参数的构造函数。来返回一个字符串类型。
AC代码
class Solution { public String reverseWords(String s) { if(s.length() == 0 || s.length() == 1) return s; int first = 0, end = 0, nextFirst = 0; char[] array = new char[s.length()]; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == ' ') { array[i] = ' '; end = i - 1; nextFirst = i + 1; } while(first <= end) { if(first < end) { array[end] = s.charAt(first); array[first] = s.charAt(end); first ++; end--; }else { array[end] = s.charAt(first); first ++; end--; } } first = nextFirst; } end = s.length()-1; while(first <= end) { if(first < end) { array[end] = s.charAt(first); array[first] = s.charAt(end); first ++; end--; }else { array[end] = s.charAt(first); first ++; end--; } } return new String(array); } }
相关文章推荐
- LeetCode——557. Reverse Words in a String III
- Leetcode557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- LeetCode Reverse Words in a String III
- 557. Reverse Words in a String III
- Reverse Words in a String III(leetcode)
- 字符串-leetcode 557 Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- leetcode Reverse Words in a String III 反转字符串中的单词
- String:557. Reverse Words in a String III
- 557. Reverse Words in a String III
- leetcode 557 Reverse Words in a String III C++
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- 557. Reverse Words in a String III
- LeetCode 557 Reverse Words in a String III(逆转字符串)