Reverse String Question

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 pointer
	public static void reverse(char[] s){
		if(s == null || s.length <= 1){
			return;
		}
		//two pointer
		for(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--;
		}
	}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章