Dada una string str y un entero k , la tarea es invertir k caracteres alternativos de la string dada. Si los caracteres presentes son menores que k, déjelos como están.
Ejemplos:
Entrada: str = “geeksforgeeks”, k = 3
Salida: eegksfgroeeks
Entrada: str = “abcde”, k = 2
Salida: bacde
Enfoque: la idea es primero invertir k caracteres, luego saltar a los siguientes k caracteres agregando 2 * k al índice y así sucesivamente hasta que se modifique la string completa.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the string after // reversing the alternate k characters string revAlternateK(string s, int k, int len) { for (int i = 0; i < s.size();) { // If there are less than k characters // starting from the current position if (i + k > len) break; // Reverse first k characters reverse(s.begin() + i, s.begin() + i + k); // Skip the next k characters i += 2 * k; } return s; } // Driver code int main() { string s = "geeksforgeeks"; int len = s.length(); int k = 3; cout << revAlternateK(s, k, len); return 0; }
Java
// Java implementation of the approach class GFG { // Function to return the string after // reversing the alternate k characters static String revAlternateK(String s, int k, int len) { for (int i = 0; i < s.length();) { // If there are less than k characters // starting from the current position if (i + k > len) break; // Reverse first k characters s = s.substring(0, i) + new String(new StringBuilder( s.substring(i, i + k)).reverse()) + s.substring(i + k); // Skip the next k characters i += 2 * k; } return s; } // Driver code public static void main(String[] args) { String s = "geeksforgeeks"; int len = s.length(); int k = 3; System.out.println(revAlternateK(s, k, len)); } } // This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach # Function to return the string after # reversing the alternate k characters def revAlternateK(s, k, Len): i = 0 while(i < len(s)): # If there are less than k characters # starting from the current position if (i + k > Len): break # Reverse first k characters ss = s[i:i + k] s = s[:i]+ss[::-1]+s[i + k:] # Skip the next k characters i += 2 * k return s; # Driver code s = "geeksforgeeks" Len = len(s) k = 3 print(revAlternateK(s, k, Len)) # This code is contributed by mohit kumar
C#
// C# implementation of the approach using System; class GFG { // Function to return the string after // reversing the alternate k characters static String revAlternateK(String s, int k, int len) { for (int i = 0; i < s.Length;) { // If there are less than k characters // starting from the current position if (i + k > len) break; // Reverse first k characters s = s.Substring(0, i) + reverse(s.Substring(i, k).ToCharArray(), 0, k - 1) + s.Substring(i + k); // Skip the next k characters i += 2 * k; } return s; } static String reverse(char []str, int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.Join("", str); } // Driver code public static void Main(String[] args) { String s = "geeksforgeeks"; int len = s.Length; int k = 3; Console.WriteLine(revAlternateK(s, k, len)); } } // This code contributed by Rajput-Ji
Javascript
<script> // Javascript implementation of the approach // Function to return the string after // reversing the alternate k characters function revAlternateK(s,k,len) { for (let i = 0; i < s.length;) { // If there are less than k characters // starting from the current position if (i + k > len) break; // Reverse first k characters s = s.substring(0, i) + s.substring(i, i + k).split("").reverse().join("") + s.substring(i + k); // Skip the next k characters i += 2 * k; } return s; } // Driver code let s = "geeksforgeeks"; let len = s.length; let k = 3; document.write(revAlternateK(s, k, len)); // This code is contributed by patel2127 </script>
eegksfgroeeks
Enfoque 2:
La idea para resolver este problema es atravesar la string y, mientras se recorre, invertir los primeros K caracteres, luego omitir los siguientes K caracteres, luego nuevamente invertir los siguientes K caracteres y así sucesivamente hasta que se modifique la string completa.
Siga los pasos para resolver el problema:
- Atraviesa hasta el final de la string original
- Recorre hacia atrás desde i+k hasta i y almacena los caracteres en la string resultante
- Actualizar i a i+k
- Recorra de i a i + k ahora, y almacene los caracteres en la string resultante
- Devolver la string original
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the string after // reversing the alternate K characters string revAlternateK(string s, int k, int n) { string ans = ""; int i = 0, j = 0; // Traverse till the end // of original string while (i < n) { // Traverse backwards from i+k to i // and store the characters // in resultant string for (j = min(i + k, n) - 1; j >= i; j--) ans += s[j]; i = min(i + k, n); // Traverse from i to i+k and store // the characters in resultant string for (j = i; j < min(i + k, n); j++) ans += s[j]; i = j; } // Return ans return ans; } // Driver code int main() { string str = "geeksforgeeks"; int N = str.length(); int K = 3; cout << revAlternateK(str, K, N); return 0; }
eegksfgroeeks
Complejidad temporal: O(N)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por Aashish Chauhan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA