sudopower

lc_151

LC: 151: Reverse words in a string

Link to problem

Solution 3 – Two pointers

func reverseWords(s string) string {
    // solution 3
    /*
        trim and split, use two pointers to keep swapping two word at ends
    */

    s = strings.Trim(s," ")
    sWords:= strings.Fields(s)  
    j:=len(sWords)-1
    i:=0
    for i<j{
        sWords[i],sWords[j]=sWords[j],sWords[i]
        i++
        j--
    }

    return strings.Join(sWords," ")

}

Solution 2 – Without array of words

func reverseWords(s string) string {
    // solution 2
    /*
        operate on string and create new string
    */
        
    var res string
    var sawSpace bool
    var word []byte
    for i:=0;i<len(s);i++{        
        if s[len(s)-i-1]==32 && sawSpace {
            // repeated space
            continue
        }

        if s[len(s)-i-1]==32{
            sawSpace=true
            res+=reverse(word)+" "
            word=nil
        } else {
            sawSpace=false
            word=append(word,s[len(s)-i-1])
        }
    }

    res+=reverse(word)+" "

    return strings.Trim(res," ")

}

func reverse(s []byte) string{
    var res []byte
    for i:=range s{
        res=append(res,s[len(s)-i-1])
    }
    return string(res)
}

Solution 1 –

func reverseWords(s string) string {
    // solution 1
    /*
        trim spaces at ends, split by space, start from last index, add reverse+space if not empty string
        join and return
    */

    s = strings.Trim(s," ")
    arr:= strings.Split(s," ")
    var res string
    for i:=len(arr)-1;i>-1;i--{
        if arr[i]!=""{
            res+=arr[i]+" "
        }
    }

    return strings.Trim(res," ")

}

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blogs