您的位置:首页 > 其它

Leetcode 541. Reverse String II(Easy)

2018-03-05 13:59 465 查看

1.题目

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]
翻译:给定一个字符串和一个整数k,从字符串的起始位置开始,每2k个字符你需要将前k个逆转。如果只剩了少于k个字符,把它们全部逆转;如果剩了少于2k个字母但是多于或等于k个字符,则将前k个字符进行逆转。
限制:1.字符串仅包含小写的英文字母。2.给定字符串和k的长度都是在[1,10000]之间。

2.思路

for循环处理,i每次增加2k。有三种情况:
①剩余的字符少于或等于k个,将他们全部逆转;
②剩余的字符多于或等于2k个,将前k个逆转,后k个原序接入。
③剩余的字符多于k个并少于2k个,将前k个逆转,剩余到字符串结尾的字符原序接入。

3.算法

public String reverseStr(String s, int k) {
int len=s.length();
StringBuilder sb=new StringBuilder();
for(int i=0;i<len;i=i+2*k){
if(i+k>=len){
sb.append(new StringBuilder(s.substring(i,len)).reverse());
}else if(i+2*k<=len){
sb.append(new StringBuilder(s.substring(i,i+k)).reverse());
sb.append(s.substring(i+k,i+2*k));
}else if(i+k<len&&i+2*k>len){
sb.append(new StringBuilder(s.substring(i,i+k)).reverse());
sb.append(s.substring(i+k,len));
}
}
return sb.toString();
}

4.总结

    这道题主要涉及的知识点有两个。

①字符串逆转,可以先把string转为stringBuilder,再调用reverse()方法。
②字符串截取,s.substring(i,j+1) 代表截取第i到第j位。如s="0123456";s.substring(1,5);则返回“1234”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: