Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to write a recursive function to check whether one array is contained in a second array (my example is also sub-array) and returns true or false.

For example: [d, e] is contained in [a, b??, c, d, e, f]

.

I know how to check without recursion (using for loops), but can not think of a solution using recursion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

The principle is the following:

0) If the first array is longer than the second one, it's not a subarray.

1) If the second array begins with the first (like [a,b] and [a,b,c,d]), then it's a subarray.

2) Else: If the first array is a subarray of the tail of the second one (that means, the part after the first element), then it's a subarray.

Just to be sure: tail([a,b,c,d]) == [b,c,d] (since I don't know how that's called in Java.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...