題目

You are 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.

Return the shuffled string.

Example 1

Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
  • 題意: indices的值為字串s替換要替換的位置
字串 : 位置
c -> 4
o -> 5
d -> 6
依此類推

解法

func restoreString(s string, indices []int) string {
	res := make([]byte, len(s))
	for k, v := range indices {
		res[v] = s[k]
	}
	return string(res)
}
  • 加個測試,看看結果是不是如預期
import (
	"github.com/stretchr/testify/assert"
	"testing"
)

func Test_restoreString(t *testing.T) {
	s := "codeleet"
	indices := []int{4, 5, 6, 7, 0, 2, 1, 3}

	assert.Equal(t, "leetcode", restoreString(s, indices))
}

參考連結