Big O Notation for space complexity of converting a string to char array

吃可爱长大的小学妹 提交于 2020-04-30 04:33:56

问题


Given a string String str= "absdf"; of N length and if we convert the same string to char Array using - char [] arr=str.toCharArray();.

Is it consider to be an extra space of O(N) or it will be O(1)?


回答1:


It is O(N) as suggested by @andy, the implementation of String.toCharArray() is something like:

public char[] toCharArray() {
  char result[] = new char[value.length];
  // copy the contents
  return result;
}



回答2:


Time Complexity will be O(N). Similar to creating a new Array equal to the length of the String and copying the String to the Character Array. Creating an array takes O(N) time and copying takes O(N). So total worst case complexity will be O(N).




回答3:


Its O(N)

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

This code is taken from openjdk implementation. We are trying to iterate each element of string and copy it into the each cell of array. Number of iteration will be length of string.



来源:https://stackoverflow.com/questions/61127378/big-o-notation-for-space-complexity-of-converting-a-string-to-char-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!