Reverse String Question

来源:互联网 发布:华为批量配置端口 编辑:程序博客网 时间:2024/06/06 03:41

Reverse String Question

1 Reverse the string word by word (from leetcode)

For example,
Given s = "the sky is blue",
return "blue is sky the".

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.

Solution 1: with extra space

use split function to split words in the string and store in an array, then append word[i] + ” “ to new string

at last return s.substring(0, s.length() -1)

这个方法面试时被问过如果不用substring, 如果做,当时想的是判断是不是最后一个就好,但是其实不对,testcase ”_1“ (这里用_表示空格)

word[] = {"" , "1"}, 所以返回还是"1_" Wrong answer!可以用deleteCharAt函数代替

if(reverse.charAt(reverse.length()-1) == ' ')reverse.deleteCharAt(reverse.length()-1);


Solution 2: Do in place O(1) Space, O(n) time

reverse twice 

first reverse: "uelb si yks eht"

second reverse each word" blue is sky the"

reverse use two pointer

code see leetcode solution


2 from yahoo interview question
和leetcode的题目不一样, 是reverse每个单词,比如 “who are you” ---> "ohw era uoy",
要求 in place,有个特殊情况是如果每个单词前后有很多空格,要保留这些空格

//two pointerpublic static void reverse(char[] s){if(s == null || s.length <= 1){return;}//two pointerfor(int i = 0, j =0; j <= s.length; j++){if(j == s.length ||s[j] == ' '){//reverse s[i] to s[j- 1]reverseWord(s, i, j- 1);while(j < s.length && s[j] == ' '){j++; // skip space}i = j;}}}private static void reverseWord(char[] s, int start, int end){//end = end-1;while(start < end){char tmp = s[start];s[start] = s[end];s[end] = tmp;start++;end--;}}



0 0
原创粉丝点击