Shuffle String

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.

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[] = { 45670213 };
        System.out.println(restoreString(s, indices));
    }

    // method to shuffle the string
    public static String restoreString(String sint[] 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 given
string restoreString(string svector<int>& indices
{
    vector<charv;
    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<intindices={3,1,4,2,0};
    str=restoreString(str,indices);
    cout<<str<<"\n";
    return 0;
}



No comments:

Post a Comment