Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C++ The complexity of string concatenation in C++ and Java

Hilton D

Active Coder
Consider the following code:
Code:
public String joinWords(String[] words) {
    String sentence = "";
    for(String w : words) {
        sentence = sentence + w;
    }
    return sentence;
}

Because each concatenation generates a new copy of the string, the overall complexity is O(n2). Fortunately, in Java, we could handle this using a StringBuffer, which has O(1) difficulty for each add, resulting in the overall complexity of O. (n).

In C++, std::string::append() has an O(n) complexity, and I'm not sure what the complexity of stringstream is.

Are there methods in C++ that are as sophisticated as those in StringBuffer?

StringBuilder Class in Java
 
Back
Top Bottom