Sherlock and Watson are playing swapping game. Watson gives to Sherlock a string S on which he has performed K swaps. You need to help Sherlock in finding the original string.
One swap on a string is performed in this way:
- Assuming 1 indexing, the i'th letter from the end is inserted between i'th and (i+1)'th letter from the starting.
Example:
Input: k = 3, s = "hrrkhceaate"
Output: hackerearth
Approach
C++
#include <bits/stdc++.h>using namespace std;string swappingGame(int k, string s){int l = s.size();int c = 0;string s3 = s + s;string s4 = s;while (s3 != s){string s1, s2;int l1 = l;if (l % 2 != 0)l1 -= 1;for (int j = 0; j < l; j += 2)s1.push_back(s4[j]);for (int j = l1 - 1; j >= 0; j -= 2)s2.push_back(s4[j]);s3 = s1 + s2;s4 = s1 + s2;c++;if (s3 == s)break;}int c1 = k % c;for (int i = 0; i < c1; i++){string s1, s2;int l1 = l;if (l % 2 != 0)l1 -= 1;for (int j = 0; j < l; j += 2)s1.push_back(s[j]);for (int j = l1 - 1; j >= 0; j -= 2)s2.push_back(s[j]);s = s1 + s2;}return s;}int main(){int k = 3;string s = "hrrkhceaate";cout << swappingGame(k, s) << "\n";return 0;}
Read Interview Questions
Exception Handling Interview Questions
DBMS Interview Questions Set -1
DBMS Interview Questions Set -2
JPA Interview Questions Set -1
Spring Boot Interview Questions Set 1
Spring Boot Interview Questions Set 2
No comments:
Post a Comment