
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Reverse String II in Python
Suppose we have a string and an integer k, we have to reverse the first k characters for every 2k characters counting from the start of the string. If there is no sufficient character left, then reverse all of them. If there are less than 2k characters but greater than or equal to k characters, then reverse the first k characters and left the other as original.
So, if the input is like "abcdefgh" and k = 3, then the output will be "cbadefhg"
To solve this, we will follow these steps −
l := make a list of characters of s
i := k-1
while i < size of l + k −
a := l[from index 0 to i-k+1]
b := l[from index i-k+1 to i+1]
c := l[from index i+1 to end]
l := a concatenate b[from index 0 to end] concatenate c
i := i + 2*k
return string by concatenating each character in l
Example
Let us see the following implementation to get a better understanding −
class Solution: def reverseStr(self, s, k): l = list(s) i = k-1 while i < len(l)+k: a = l[:i-k+1] b = l[i-k+1:i+1] c = l[i+1:] l = a + b[::-1] + c i += 2*k return ''.join(l) ob = Solution() print(ob.reverseStr("abcdefg", 3))
Input
"abcdefg", 3
Output
cbadefg
- Related Articles
- Reverse String in Python
- Reverse Words in a String II in C++
- Reverse Vowels of a String in Python
- How to reverse a string in Python?
- Reverse words in a given String in Python
- How to reverse a string in Python program?
- String reverse vs reverse! function in Ruby
- Python Program to Reverse a String Using Recursion
- Python Program to Reverse a String without using Recursion
- Reverse a string in C#
- How to reverse String in Java?
- Reverse a string in C/C++
- Reverse Linked List II in C++\n
- Reverse Integer in Python
- Reverse Words in a String in C++
