Given a string s and an integer array indices of the same length
The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Example:
Input: s = "aiohn", indices
= [3,1,4,2,0]
Output: "nihao"
Approach
Java
public class ShuffleString {public static void main(String[] args) {String s = "codeleet";int indices[] = { 4, 5, 6, 7, 0, 2, 1, 3 };System.out.println(restoreString(s, indices));}// method to shuffle the stringpublic static String restoreString(String s, int[] indices) {char c[] = new char[s.length()];for (int i = 0; i < indices.length; i++) {c[indices[i]] = s.charAt(i);}return new String(c);}}
C++
#include <bits/stdc++.h>using namespace std;//function to restore the string//according to the indices givenstring restoreString(string s, vector<int>& indices){vector<char> v;v.resize(indices.size());for(int i=0;i<indices.size();i++)v[indices[i]]=s[i];string res="";for(int i=0;i<v.size();i++)res+=v[i];return res;}int main(){string str="aiohn";vector<int> indices={3,1,4,2,0};str=restoreString(str,indices);cout<<str<<"\n";return 0;}
No comments:
Post a Comment