[LeetCode] 344 Reverse String && 541 Reverse String II

时间:2021-07-12 20:50:56

原题地址:

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 = ; i <= (size - ) / ; i++) {
int temp = s[i];
s[i] = s[size - i - ];
s[size - i - ] = 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 = * k;
int m = s.size() / double_k;
int n = s.size() % double_k;  //剩余部分
for (int i = ; i < m; i++) {
for (int j = ; j <= (k - ) / ; j++) {
char temp = s[i * double_k + j];
s[i * double_k + j] = s[double_k * i + k - j - ];
s[double_k * i + k - j - ] = temp;
}
}
if (n == ) return s;
int end = n >= k ? k : n;
for (int j = ; j <= (end - ) / ; j++) {
char temp = s[m * double_k + j];
s[m * double_k + j] = s[double_k * m + end - j - ];
s[double_k * m + end - j - ] = temp;
}
return s;
}
};