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 fewer 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"
Approach
Java
package com.practic.string;public class ReverseStringII {public static void main(String[] args) {String s = "abcdefg";int k = 2;System.out.println(reverseStr(s, k));}static String reverseStr(String s, int k) {int n = s.length();if (n == 0 || k == 0)return s;int i = 0;while (i < n) {s = reverse(s, i, +Math.min(i + k, n)-1);i += 2 * k;}return s;}private static String reverse(String s, int i, int j) {char[] cS = s.toCharArray();while (i < j) {char c = cS[i];cS[i] = cS[j];cS[j] = c;i++;j--;}return new String(cS);}}
C++
#include <bits/stdc++.h>using namespace std;string reverseStr(string s, int k){int n = s.size();if (n == 0 || k == 0)return s;int i = 0;while (i < n){reverse(s.begin() + i, s.begin() + min(i + k, n));i += 2 * k;}return s;}int main(){string s = "abcdefg";int k = 2;cout << reverseStr(s, k);return 0;}
No comments:
Post a Comment