問題(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.
大意:
給出一個(gè)字符串辩棒,你需要翻轉(zhuǎn)句子中每個(gè)單詞的字母邦尊,但保證空格位置以及原始的單詞順序不變黔寇。
例1:
輸入:"Let's take LeetCode contest"
輸出: "s'teL ekat edoCteeL tsetnoc"注意:在字符串中,每個(gè)單詞都被單個(gè)空格分開,不會(huì)有額外的空格。
思路:
遍歷字符串,沒遇到一個(gè)空格就開始處理前面的這個(gè)單詞揩环,將其用一些方式進(jìn)行反轉(zhuǎn)后存入新的字符串中,然后記得在新字符串后面加個(gè)空格(最后一個(gè)單詞就不要加空格了)幅虑。
如何對(duì)單詞反轉(zhuǎn)有多種方式丰滑,可以用一個(gè)臨時(shí)容器來存儲(chǔ),遇到單詞中每個(gè)字母都將其插入到容器首部翘单,然后再將整個(gè)容器的內(nèi)容放到字符串中就好了吨枉。這個(gè)容器可以是deque這種允許兩端插入的蹦渣,也可以就是string。但是用string(49ms)居然比用在首部插入應(yīng)該更快的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的部分區(qū)間進(jìn)行反轉(zhuǎn)柬唯,那就只需要記錄空格的位置,然后將之間的區(qū)域進(jìn)行反轉(zhuǎn)就行了圃庭,也不用創(chuàng)建結(jié)果字符串锄奢,直接在原字符串上操作即可,速度快了一倍剧腻。
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