LeetCode: Reverse Words in a String && Rotate Array

时间:2023-12-17 17:14:08

Title:

Given an input string, reverse the string word by word.

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

https://leetcode.com/problems/reverse-words-in-a-string/

思路:先将字符串全部逆转,在将每个单词逆转。具体实现,要注意空格,所以对字符串倒过来处理。

class Solution {
public:
void reverseWords(string &s)
{
string rs;
for (int i = s.length()-; i >= ; )
{
while (i >= && s[i] == ' ') i--;
if (i < ) break;
if (!rs.empty()) rs.push_back(' ');
string t;
while (i >= && s[i] != ' ') t.push_back(s[i--]);
reverse(t.begin(), t.end());
rs.append(t);
}
s = rs;
}
};

Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

https://leetcode.com/problems/rotate-array/

思路:一样,先将整个字符串反转,在对每个部分反转。另外注意k可能大于size。

class Solution {
public:
void rotate(vector<int>& nums, int k) {
if ( k < )
return ;
int size = nums.size();
k = (k-) % size + ;
reverse(nums,,size-);
reverse(nums,,k-);
reverse(nums,k,size-);
}
void reverse(vector<int>& nums,int start, int end){
while (start < end){
nums[start] ^= nums[end];
nums[end] ^= nums[start];
nums[start++] ^= nums[end--];
}
}
};