[LeetCode] 344 Reverse String & 541 Reverse String II
Posted fengzw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 344 Reverse String & 541 Reverse String II相关的知识,希望对你有一定的参考价值。
原题地址:
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:
- The string consists of lower English letters only.
- 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的主要内容,如果未能解决你的问题,请参考以下文章