Java solution O(n)


  • 0
    S

    Some of the other solution make use of library methods. I believe the objective of this problem is not use them.

    class Solution {
        public String reverseString(String s) {
          char[] c = s.toCharArray();
          int len = s.length();
          char tmp;
          for(int ptr = 0, last = len-1; ptr<len/2; ptr++, last--) {
            if(ptr==last) break;
            //swap s[ptr] and s[last]
            tmp = c[ptr];
            c[ptr] = c[last];
            c[last] = tmp;
          }  
          return new String(c);
        }
    }
    

Log in to reply
 

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