541. Reverse String II

来源:互联网 发布:华科软件学院 编辑:程序博客网 时间:2024/04/30 08:17

Given a string and an integer k, you need toreverse the first k characters for every 2k characters counting from the startof 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, thenreverse the first k characters and left the other as original.

Input: s = "abcdefg", k = 2

Output: "bacdfeg"

    翻译:给定一个字符串和一个整数k,你需要反转从字符串开始计数的每2k个字符的前k个字符。如果剩余少于k个字符,则将所有字符都反转。如果小于2k但大于或等于k个字符,则反转前k个字符,并将另一个作为原始字符。

    直接按照上面的情况分类就好了,比较简单。自己定义一个从任意其实位置到结束位置的字符串反转的方法,然后分情况讨论,找好起始点就行了。代码如下:

public class Solution {

    public static char[] reverse(char[] a,intstart,int end){

           char temp;

           int length=end-start;

                 //反转所有zifu

                 for(int i=0;i<length/2;i++){

                      temp=a[i+start];

                      a[i+start]=a[end-i-1];

                      a[end-i-1]=temp;

                 }

                 return a;

          

      }

    public String reverseStr(String s, int k) {

    

           char []ch =s.toCharArray();

           int length=ch.length;

           int count=length;

           int flag=0;

           while(count>0){

                 if(count<k){

                      //反转所有zifu

                      ch=reverse(ch,flag,length);

                      break;

                 }

                 if(count>=k&&count<2*k){

                      ch=reverse(ch,flag,flag+k);

                      break;

                 }

                 if(count>=2*k){

                      ch=reverse(ch,flag,flag+k);

                      flag+=2*k;

                      count=length-flag;

                 }

           }

           return new String(ch);

    }

}

0 0
原创粉丝点击