[LeetCode] Reverse String II 翻轉字符串之二


 

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

 

Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

 

Restrictions:

  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

 

這道題是之前那道題Reverse String的拓展,同樣是翻轉字符串,但是這里是每隔k隔字符,翻轉k個字符,最后如果不夠k個了的話,剩幾個就翻轉幾個。比較直接的方法就是先用n/k算出來原字符串s能分成幾個長度為k的字符串,然后開始遍歷這些字符串,遇到2的倍數就翻轉,翻轉的時候注意考慮下是否已經到s末尾了,參見代碼如下:

 

解法一:

class Solution {
public:
    string reverseStr(string s, int k) {
        int n = s.size(), cnt = n / k;
        for (int i = 0; i <= cnt; ++i) {
            if (i % 2 == 0) {
                if (i * k + k < n) {
                    reverse(s.begin() + i * k, s.begin() + i * k + k);
                } else {
                    reverse(s.begin() + i * k, s.end());
                }
            }
        }
        return s;
    }
};

 

在論壇里又發現了寫法更為簡潔的方法,就是每2k個字符來遍歷原字符串s,然后進行翻轉,翻轉的結尾位置是取i+k和末尾位置之間的較小值,感覺很叼,參見代碼如下:

 

解法二:

class Solution {
public:
    string reverseStr(string s, int k) {
        for (int i = 0; i < s.size(); i += 2 * k) {
            reverse(s.begin() + i, min(s.begin() + i + k, s.end()));
        }
        return s;
    }
};

 

類似題目:

Reverse String

 

參考資料:

https://discuss.leetcode.com/topic/82652/one-line-c/2

https://discuss.leetcode.com/topic/82626/java-concise-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM