【LeetCode】541. Reverse String II 解題報告(Python)
阿新 • • 發佈:2019-01-05
題目描述
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個字元進行翻轉,然後後面k個數字正常,進行拼接到一起。
解題方法
Java解法
也是很簡單的題,但是我竟然耽誤了很久。主要問題出現在了reverse函式上。我犯了錯誤。因為這個i不是從0開始的,那麼,end-1-i的時候一定要再加上start才可以,負責不是end的下一個字元。只要細心還是可以做對的,實在不行就得用debug了。
public class Solution {
public String reverseStr(String s, int k) {
char[] ans = s.toCharArray();
int len = s.length();
for (int i = 0; i < len; i += 2 * k) {
if (len - i < k) {
reverse(ans, i, len);
} else {
reverse(ans, i, i + k);
}
}
return new String(ans);
}
public void reverse(char[] chars, int start, int end){
for (int i = start; i < (start + end) / 2; i++) {
char temp = chars[i];
chars[i] = chars[end - 1 - i + start];
chars[end - 1 - i + start] = temp;
}
}
}
Python解法
Python的切片就是做這個的!而且切片很友好,如果切到外邊的話也無所謂,因為Python會把切到外邊的自動過濾掉。
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
N = len(s)
res = ""
pos = 0
while pos < N:
nx = s[pos : pos + k]
res = res + nx[::-1] + s[pos + k : pos + 2 * k]
pos += 2 * k
return res
日期
2017 年 4 月 12 日
2018 年 11 月 17 日 —— 美妙的週末,美麗的天氣