0

I have Map<String, String> which contains elements like: {“a”=”b”, “b”=”c”, “c”=”d”, “z”=”y”, …}.

I need a method:

List<String> getTransitiveKeys(String startKey);// assuming the map is visible somehow as `map`

When getTransitiveKeys(“a”) is called, it will return [“a”, “b”, “c”]. When getTransitiveKeys (“z”) is called, it will return [“z”].

Recursion needed in the method?

Thanks!

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130

2 Answers2

4
List<String> getTransitiveKey(String key) {
   List<String> result = new LinkedList<String>();
   while(map.containsKey(key)) {
    // avoid endless loops
    if(result.contains(key)) {
      break;
    }

    result.add(key);  
    key = map.get(key)
  }
  return result;
}
lweller
  • 11,077
  • 3
  • 34
  • 38
0

why recursion ? just a single loop

while(map.get(startKey) != null) {
    startKey =  map.get(startKey);
}