541. Reverse String II #92
quinnwencn
started this conversation in
General
Replies: 2 comments
-
AnalysisIn Cpp, it is easy to use std::reverse to reverse the range k of the string. But you need to pay attention to the case that k is bigger than the length of the string. Solution written in Cppclass Solution {
public:
string reverseStr(string s, int k) {
int n=s.size();
if(n<k){
reverse(s.begin(), s.end());
return s;
}
int q=n/(2*k); //kitne baar k out of 2k ko reverse karna h
int r=n%(2*k); // last me kitne elements bachenge
for(int i=0;i<q*(2*k);i+=2*k){
int first1=i;
int last1=i+k-1;
while(first1<last1){
swap(s[first1], s[last1]);
// int temp=s[last1];
// s[last1]=s[first1];
// s[first1]=temp;
first1++;
last1--;
}
}
if(r<k){
int first2=n-r;
int last2=n-1;
while(first2<last2){
// int temp=s[last2];
// s[last2]=s[first2];
// s[first2]=temp;
swap(s[first2], s[last2]);
first2++;
last2--;
}
}else if(k<=r && r<2*k){
int first3=n-r;
int last3=n-r+k-1;
while(first3<last3){
swap(s[first3], s[last3]);
// int temp=s[last3];
// s[last3]=s[first3];
// s[first3]=temp;
first3++;
last3--;
}
}
return s;
}
};Solution written in Rustimpl Solution {
pub fn reverse_str(mut s: String, k: i32) -> String {
let mut need_reverse = true;
s.chars().collect::<Vec<char>>().chunks(k as usize)
.into_iter()
.map(|chunk| {
if need_reverse {
need_reverse = false;
chunk.iter().rev().collect::<String>()
} else {
need_reverse = true;
chunk.iter().collect::<String>()
}
})
.collect::<String>()
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
An amazing solution saw on leetcode: impl Solution {
pub fn reverse_str(mut s: String, k: i32) -> String {
unsafe { s.as_bytes_mut() }.chunks_mut(k as usize).step_by(2).for_each(|x| x.reverse());
s
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Description
Given a string s and an integer k, 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 leave the other as original.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2
Output: "bacd"
Constraints:
1 <= s.length <= 104
s consists of only lowercase English letters.
1 <= k <= 104
Beta Was this translation helpful? Give feedback.
All reactions