1. 程式人生 > >[LeetCode] 344 Reverse String & 541 Reverse String II

[LeetCode] 344 Reverse String & 541 Reverse String II

let 庫函數 code only urn out pro 滿足 function

原題地址:

344 Reverse String:

https://leetcode.com/problems/reverse-string/description/

541 Reverse String II:

https://leetcode.com/problems/reverse-string-ii/description/

題目&解法:

1.Reverse String:

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

這個直接上代碼就行了,關於字符串翻轉,不管字符數目是奇數還是偶數,都是一樣的方法(當然可以調用庫函數):

class Solution {
public:
    string reverseString(string s) {
        int size = s.size();
        for (int i = 0; i <= (size - 1) / 2; i++) {
            int temp = s[i];
            s[i] = s[size - i - 1];
            s[size - i - 1] = temp;
        } 
        
return s; } };

2. 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]

也是很簡單的一道題目,我的做法是這樣的:先對前面滿足2k的部分進行前k位的翻轉,剩余不足的進行討論,確認有幾位需要翻轉:

class Solution {
public:
    string reverseStr(string s, int k) {
       int double_k = 2 * k;
        int m = s.size() / double_k;
        int n = s.size() % double_k;  //剩余部分
        for (int i = 0; i < m; i++) {
            for (int j = 0; j <= (k - 1) / 2; j++) {
                char temp = s[i * double_k + j];
                s[i * double_k + j] = s[double_k * i + k - j - 1];
                s[double_k * i + k - j - 1] = temp;
            }
        }
        if (n == 0) return s;
        int end = n >= k ? k : n;
        for (int j = 0; j <= (end - 1) / 2; j++) {
            char temp = s[m * double_k + j];
            s[m * double_k + j] = s[double_k * m + end - j - 1];
            s[double_k * m + end - j - 1] = temp;
        }
        return s;
    }
};

[LeetCode] 344 Reverse String & 541 Reverse String II