Leetcode|Reverse Words in a String
Given s = “the sky is blue”,
* return “blue is sky the”.
這種問題一般有三種解法:
1,One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.
這種方法需要額外空間儲存單詞,而且需要遍歷兩邊。
2,We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.
需要額外空間,從後面遍歷,只需要遍歷一次。(當然如果用C,需要先遍歷一次獲取尾部)
3,in-place 方法:需要O(1)的額外空間,多次翻轉的方法;(如果單詞之間以前開頭和結尾處有很多空格,處理會麻煩一些,很考驗人)
Reverse Words in a String .II
* Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
*
* The input string does not contain leading or trailing spaces and the words are always separated by a single space.
*
* For example,
* Given s = “the sky is blue”,
* return “blue is sky the”.
*
* Could you do it in-place without allocating extra space?
如果不考慮空格問題,非常容易利用多次反轉解決。
//先定義reverse函式,翻轉字串
void reverse(char *s,int start, int last){
while(start<last){
char temp=s[start];
s[start++]=s[last];
s[last--]=temp;
}
}
void reverseWords_no_space(char *s){
int j;//len
for(j=0;s[j]!='\0';j++);//找到尾部
reverse(s,0,j-1);
for(int begin=0,i=0;i<=j;i++){
if(s[i]==' ' ||s[i]=='\0'){
reverse(s,begin,i-1);
begin=i+1;
}
}
}
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”.
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
void reverse(char *s,int start, int last){
while(start<last){
char temp=s[start];
s[start++]=s[last];
s[last--]=temp;
}
}
void reverseWords(char *s) {//只有一個單詞,就把兩邊的空格去掉
int index=0;//先用於記錄長度
//i為不為空格的第一位
for(index=0;s[index]!='\0';index++);//找到尾部
reverse(s,0,index-1);
for(int i=0,begin=0;i<=index;i++){//反轉單詞
if(s[i]==' '||s[i]=='\0') continue;
else {
begin=i;
for(;s[i]!=' '&&s[i]!='\0';i++);
reverse(s,begin,i-1);
begin=i+1;
}
}
for(int i=0,newi=0,extraspace=true;i<=index;i++){
if(s[i]!=' '||(s[i]==' '&&!extraspace)){//保證單詞之間以及開頭處不會有多餘的空格
if(s[i]!='\0') s[newi++]=s[i];
else {
if(newi>0&&s[newi-1]==' ') s[--newi]='\0';//處理結尾的空格
else s[newi]='\0';
return;
}
if(s[i]==' ') extraspace=true;
else extraspace=false;
}
}
}