問題(Easy):
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.
Example 1:
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:
輸入:"Let's take LeetCode contest"
輸出: "s'teL ekat edoCteeL tsetnoc"注意:在字符串中,每個單詞都被單個空格分開,不會有額外的空格。
思路:
遍歷字符串,沒遇到一個空格就開始處理前面的這個單詞,將其用一些方式進行反轉后存入新的字符串中,然后記得在新字符串后面加個空格(最后一個單詞就不要加空格了)。
如何對單詞反轉有多種方式,可以用一個臨時容器來存儲,遇到單詞中每個字母都將其插入到容器首部,然后再將整個容器的內容放到字符串中就好了。這個容器可以是deque這種允許兩端插入的,也可以就是string。但是用string(49ms)居然比用在首部插入應該更快的deque(768ms)要快得多。
代碼(C++):
// 用deque
class Solution {
public:
string reverseWords(string s) {
deque<char> que;
string res = "";
for (int i = 0; i < s.length(); i++) {
if (s[i] != ' ') {
que.push_front(s[i]);
} else {
auto iter = que.begin();
while (iter != que.end()) {
res = res + *iter;
iter++;
}
que.clear();
res = res + " ";
}
}
auto iter = que.begin();
while (iter != que.end()) {
res = res + *iter;
iter++;
}
return res;
}
};
// 用string
class Solution {
public:
string reverseWords(string s) {
string res = "";
int pos = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] != ' ') {
res.insert(pos, s.substr(i, 1));
} else {
res = res + " ";
pos = i + 1;
}
}
return res;
}
};
他山之石:
原來C++可以直接操作讓string的部分區間進行反轉,那就只需要記錄空格的位置,然后將之間的區域進行反轉就行了,也不用創建結果字符串,直接在原字符串上操作即可,速度快了一倍。
class Solution {
public:
string reverseWords(string s) {
for (int i = 0; i < s.length(); i++) {
if (s[i] != ' ') { // when i is a non-space
int j = i;
for (; j < s.length() && s[j] != ' '; j++) { } // move j to the next space
reverse(s.begin() + i, s.begin() + j);
i = j - 1;
}
}
return s;
}
};
合集:https://github.com/Cloudox/LeetCode-Record