ReverseString, a C# interview-question

前端 未结 12 1975
予麋鹿
予麋鹿 2021-01-31 06:15

I had an interview question that asked me for my \'feedback\' on a piece of code a junior programmer wrote. They hinted there may be a problem and said it will be used heavily o

12条回答
  •  耶瑟儿~
    2021-01-31 07:14

    Since strings are immutable, each += statement will create a new string by copying the string in the last step, along with the single character to form a new string. Effectively, this will be an O(n2) algorithm instead of O(n).

    A faster way would be (O(n)):

    // pseudocode:
    static string ReverseString(string input) {
        char[] buf = new char[input.Length];
        for(int i = 0; i < buf.Length; ++i)
           buf[i] = input[input.Length - i - 1];
        return new string(buf);
    }
    

提交回复
热议问题