Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

java - Recursive function to check whether sub-array

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

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

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...