我有一个Person对象结构如下,我想根据他的名字搜索一个Person。
public Person{ String name; List<Person> person; }我们如何实现这个搜索方法?
将有一个根对象是Person,并且它具有与其他人的链接等。
人的名字是独一无二的。
搜索签名可能是
public Person findPerson(Person root, String name){ }我可以把它看作是这个或这个 。
任何人都可以提出任何其他解决方案吗?
I have a object structure for Person as below and I want to search a Person on the based of his name.
public Person{ String name; List<Person> person; }How can we implement search method for this?
There will be one root object which is Person and it has link to other persons and so on.
And the names of Persons are unique.
The search signature could be
public Person findPerson(Person root, String name){ }I can look it as this or this.
Can anyone suggest any other solution for this?
最满意答案
你将需要递归。 遍历列表中的所有人并在该人内搜索相同的目标。 一旦你找到你的目标,返回并停止所有搜索。
这里是一些伪代码:
Person search(Person, Name) if (Person.Name == Name) return Person; for each subPerson in Person.person: Person found = subPerson.search(Person, Name); if (found != null) return found; return null;You will need recursion. Iterate over all the persons in the List and search within that person for the same target. Once you found your target, return and stop all searching.
Here is some pseudo code:
Person search(Person, Name) if (Person.Name == Name) return Person; for each subPerson in Person.person: Person found = subPerson.search(Person, Name); if (found != null) return found; return null;更多推荐
发布评论