Simple Java in place with time complexity no stringbuilder no reverse no split function.


  • 0
    R

    Java in place replace code. Time complexity is O(nK) n is the length of string and K is the average length of the word in a string. This can also be done using stringbuilder and calling reverse function of string builder. It's always better to avoid inbuilt functions in interviews. This can also be done using java split and reverse funcitons.

    public class Solution {
        public String reverseWords(String s) {
            int i=0;
            if(s == null)
            return null;
            char[] ss = s.toCharArray();
            while(i<ss.length){
                int j=i,k=0;
                while(j<ss.length && ss[j]!=' ')
                    j++;
                k=j-1;
                while(i<k){
                    char temp = ss[i];
                    ss[i]=ss[k];
                    ss[k] = temp;
                    k--;i++;
                }
                i=j+1; 
            }
        return new String(ss);
        }
    }
    

Log in to reply
 

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