541. Reverse String II

LeetCode easy original: C# #array #csharp #easy #leetcode #math #string
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

Дана cadena s и entero k, переreturn первые k символов для каждых 2k символов, начиная с начала строки.

Если осталось меньше k символов, переreturn все. Если осталось меньше 2k, но больше или равно k символов, переreturn первые k символов и оставьте остальные как есть.

Ejemplo:

Input: s = "abcdefg", k = 2

Output: "bacdfeg"

C# solución

coincidente/original
class Solution {
    public string ReverseStr(string s, int k) {
        char[] a = s.ToCharArray();
        for (int start = 0; start < a.Length; start += 2 * k) {
            int i = start, j = Math.Min(start + k - 1, a.Length - 1);
            while (i < j) {
                char tmp = a[i];
                a[i++] = a[j];
                a[j--] = tmp;
            }
        }
        return new string(a);
    }
}

C++ solución

borrador automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
    public string ReverseStr(string s, int k) {
        char[] a = s.ToCharArray();
        for (int start = 0; start < a.size(); start += 2 * k) {
            int i = start, j = min(start + k - 1, a.size() - 1);
            while (i < j) {
                char tmp = a[i];
                a[i++] = a[j];
                a[j--] = tmp;
            }
        }
        return new string(a);
    }
}

Java solución

coincidente/original
class Solution {
    public String reverseStr(String s, int k) {
        char[] a = s.toCharArray();
        for (int start = 0; start < a.length; start += 2 * k) {
            int i = start, j = Math.min(start + k - 1, a.length - 1);
            while (i < j) {
                char tmp = a[i];
                a[i++] = a[j];
                a[j--] = tmp;
            }
        }
        return new String(a);
    }
}

JavaScript solución

coincidente/original
class Solution {
    reverseStr(s, k) {
        let a = s.split('');
        for (let start = 0; start < a.length; start += 2 * k) {
            let i = start, j = Math.min(start + k - 1, a.length - 1);
            while (i < j) {
                [a[i], a[j]] = [a[j], a[i]];
                i++;
                j--;
            }
        }
        return a.join('');
    }
}

Python solución

coincidente/original
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        a = list(s)
        for start in range(0, len(a), 2 * k):
            i, j = start, min(start + k - 1, len(a) - 1)
            while i < j:
                a[i], a[j] = a[j], a[i]
                i += 1
                j -= 1
        return ''.join(a)

Go solución

coincidente/original
func reverseStr(s string, k int) string {
    a := []rune(s)
    for start := 0; start < len(a); start += 2 * k {
        i, j := start, min(start+k-1, len(a)-1)
        for i < j {
            a[i], a[j] = a[j], a[i]
            i++
            j--
        }
    }
    return string(a)
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

Algorithm

Разворачиваем каждый блок из 2k символов непосредственно. Каждый блок начинается с кратного 2k: наEjemplo, 0, 2k, 4k, 6k и так далее.

Будьте внимательны, если символов недостаточно, блок может не быть перевернут.

Для разворота блока символов с позиции i до j, меняем местами символы на позициях i++ и j--.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.