Check if two arrays are cyclic permutations

前端 未结 4 1108
情歌与酒
情歌与酒 2021-02-14 08:41

Given two arrays, how do you check if one is a cyclic permutation of the other?

For example, given a = [1, 2, 3, 1, 5], b = [3, 1, 5, 1, 2], an

4条回答
  •  没有蜡笔的小新
    2021-02-14 08:55

    The standard trick here is to concatenate one of the arrays with itself, and then try to find the 2nd array in the concatenated array.

    For example, 'a' concatenated with itself is:

    [1, 2, 3, 1, 5, 1, 2, 3, 1, 5]

    Since you do see 'b' in this array starting from the 3rd element then a and b are cyclic permutations.

提交回复
热议问题