String Manipulation


  • 0

    Click here to see the full article post


  • 0
    K

    Similar advice holds for Python. Instead of concatenation in a loop, form a list of strings and then use "".join(string_list) after the loop has completed.


  • 0
    A

    How about string addition in Python. like 'Hello'+'world'


  • 0
    L

    How about Javascript? Is there similar function like StringBuilder?


  • 0
    K

    String is immutable in C# as well.


  • 0
    X

    I also can't understand why String operate is O(n^2), would someone like explaining it?


  • 0
    W

    @xiaowu4 Strings concatenation operates in O(n) but in the case above they were talking about it being O(n^2) because it was concatenating inside the for loop which is already O(n).


  • 0
    J

    Very useful.


  • -1
    P

    In python + is faster than ''.join() and there is nothing called append().

    %timeit "a"*10 + "b"*10
    The slowest run took 6.07 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000000 loops, best of 3: 224 ns per loop

    %timeit ''.join(['a'*10, 'b'*10])
    The slowest run took 9.30 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000000 loops, best of 3: 369 ns per loop


  • 1

    @poo-sesha-gmail-com You should test concatenating n strings, not just two. And the Python equivalent is to collect the parts in a list, which does have append.


  • 0
    S

    To concatenate string efficiently, just use StringBuilder


  • 0
    L

    quite simple contents, haha


  • 0
    F

    Could someone explain why char[] will incur extra space after converted from string?


  • 0
    G

    @FiftyShades , this is because you had the variable S but created an array to hold a number of characters (s.Length)


  • 0
    A

    @Artix Let me answer my own question:

    For python, we can use a list(mutable data type) to represent the whole string.
    Append one 'hello' each time.
    At last, use ''.join to forge the whole string.

    li=[]
    s = '';
    for i in range(n):
        li.append('hello')';
    s = ''.join(li)
    

    This runtime should be O(n).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.