C# O(n/2) solution


  • 0
    K

    I forgot that the string in C# were unchangeable and tried to do it in place. Of course it did not compile. So I had to use extra space that is array of chars.

    public class Solution {
        public string ReverseString(string s) {
            int len = s.Length;
            char[] t = new char[len];
            int i=0;
            while (i<len/2)
            {
                t[i] = s[len-1-i];
                t[len-1-i] = s[i];
                i++;
            }
            if (len%2==1) t[i] = s[i]; //middle character (if exists)
            return String.Join("",t);
        }
    }
    

  • 0
    Y

    Some slight improvement here.

    public class Solution {
        public string ReverseString(string s) {
            int len = s.Length;
            StringBuilder t = new StringBuilder(s);
            for(int i = 0, j = len-1; i < len/2; i++, j--)
            {
                t[i] = s[j];
                t[j] = s[i];
            }
            return t.ToString();
        }
    }
    

    I use StringBuilder instead of char[].
    If you prefer using char[], then replace the following lines

    StringBuilder t = new StringBuilder(s);
    return t.ToString();
    

    with

    char[] t = s.ToCharArray();
    return new string(t);
    

  • 0
    K

    @yles9056 thanks, it seems more compact and we don't need to deal with the middle character like the in-place solution i tried first


Log in to reply
 

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