简体   繁体   English

Java递归:如何传递String

[英]Java recursion: how to pass a String

I am examining this code problem: 我正在研究这个代码问题:

Given a dictionary, write a function to flatten it. 给定一个字典,编写一个函数来展平它。

Consider the following input/output scenario for better understanding: 请考虑以下输入/输出方案以便更好地理解:

Input:

{
  'Key1': '1',
  'Key2': {
    'a' : '2',
    'b' : '3',
    'c' : {
      'd' : '3',
      'e' : '1'
      }
    }
}

Output:
{
  'Key1': '1',
  'Key2.a': '2',
  'Key2.b' : '3',
  'Key2.c.d' : '3',
  'Key2.c.e' : '1'
}

The accepted solution is below (please note this is pseudocode only). 接受的解决方案如下(请注意这只是伪代码)。

I want to implement it in Java 我想用Java实现它

function flattenDictionary(String initialKey, dictionary, flatDictionary){

  for (key : dictionary.keyset()){
      value = dictionary.get(key)

      if (!isHashMapInstance(value)){ 
          if (initialKey == null || initialKey == "")
              flatDictionary.put(key, value)
          else
              flatDictionary.put(initialKey + "." + key, value)             
      }
      else { 
        if (initialKey == null || initialKey == "")
          flattenDictionary(key, value, flatDictionary)
        else
          //-----> Here we are creating a new String for each recursive call !!!!<----
          flattenDictionary(initialKey + "." + key, value, flatDictionary)
      }
  }
}

My doubt is at the the arrow. 我怀疑是在箭头上。

We recursively pass to the flattenDictionary() method a new String each time by concatenating the initialKey with the new key that we got from the Map. 我们通过将initialKey与我们从Map获得的新key连接initialKey ,每次递归传递给flattenDictionary()方法一个新的String。

Here we are potentially creating many long Strings! 在这里,我们可能会创建许多长字符串!

Is it possible to avoid creating all those Strings? 是否有可能避免创建所有这些字符串?

I don't think that passing StringBuilder could be a solution, because we would end up with wrong results 我不认为传递StringBuilder可能是一个解决方案,因为我们最终会得到错误的结果

You can use a StringBuilder if you undo your changes after the recursive call. 如果在递归调用后撤消更改,则可以使用StringBuilder。 Assuming initialKey is now an instance of StringBuilder , you can do something like this: 假设initialKey现在是StringBuilder一个实例,你可以这样做:

int originalLength = initialKey.length()
initialKey.append(".").append(key)

flattenDictionary(initialKey, value, flatDictionary)

initialKey.setLength(originalLength) // undo: delete the appended chars

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM