LeetCode: Reverse Words in a String && Rotate Array

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()-1; i >= 0; )
        {
            while (i >= 0 && s[i] == ' ') i--;
            if (i < 0) break;
            if (!rs.empty()) rs.push_back(' ');
            string t;
            while (i >= 0 && 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 < 0)
            return ;
        int size = nums.size();
        k = (k-1) % size + 1;
        reverse(nums,0,size-1);
        reverse(nums,0,k-1);
        reverse(nums,k,size-1);
    }
    void reverse(vector<int>& nums,int start, int end){
        while (start < end){
            nums[start] ^= nums[end];
            nums[end] ^= nums[start];
            nums[start++] ^= nums[end--];
        }
    }
};

 

posted on 2015-06-06 10:52  月下之风  阅读(223)  评论(0编辑  收藏  举报

导航