Javascript solution without any String build-in methods


  • 0
    X

    var reverseWords = function(str) {
    var nS = '', isTriming = true, i, res = '', w = '';

    for(i=0; i<str.length; i++) {
        if(isTriming && str[i] === ' ') {
            continue;
        } else {
            isTriming = false;
            
            // colapse spaces
            if(str[i] === ' ') {
                if(i < str.length -1 && str[i+1] !== ' ') {
                    nS = ' ' + nS;
                } else {
                    continue;
                }
            } else {
                nS = str[i] + nS;
            }
        }
    }
    
    for(i=0; i<nS.length; i++) {
        if(nS[i] === ' ') {
            res += (w + ' ');
            w = '';
        } else {
            w = nS[i] + w;
        }
    }
    
    res += w;
    return res;
    

    };


Log in to reply
 

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