Skip to content

Latest commit

 

History

History
65 lines (49 loc) · 1.43 KB

20210113.md

File metadata and controls

65 lines (49 loc) · 1.43 KB

Algorithm

541. Reverse String II

Description

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]

Solution

class Solution {
    public String reverseStr(String s, int k) {
        for(int i=0;i<s.length();i+=2*k){
            while(i+k>s.length()){
                k--;
            }
            s = s.substring(0,i)+new String(new StringBuffer(s.substring(i,i+k)).reverse())+s.substring(i+k);
        }
        return s;
    }
}
class Solution {
   public String reverseStr(String s, int k) {
    	char[] ch = s.toCharArray();
        for(int i=0;i<s.length();i+=2*k) {
        	reverse(ch,i ,i+k);
        }
        return String.valueOf(ch);
    }
    private void reverse(char[] ch, int i,int j) {
    	j = Math.min(ch.length, j)-1;
    	for(;i<j;i++,j--) {
    		char temp = ch[i];
    		ch[i] = ch[j];
    		ch[j] = temp;
    	}
    }
}

Discuss

Review

Tip

Share