Java strings are immutable. Every time you do:
s+=c;
You're really saying:
s = new String(s + c);
new String(s + c) must allocate a string of length s + 1, or:
1
2
3
4
5
6
7
8
9
...
etc.
Since Sum(1..N) == (n + 1) (n / 2), this is O(n^2).
One of the cases where StringBuilder is a definite advantage.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…