Reverse words in String

[Question] Given a string s, reverse the words of the string.
Note: Remove extra spaces from output

Examples:

Example 1:
Input: s=”My Name is Janesh”
Output: “Janesh is Name My”

Example 2:
Input: s= "  My     Name    is Janesh"
Output: "Janesh is Name My"
// TC: O(N)
// SC: O(1)
func reverseWords(_ s: String)-> String {
    var left = 0
    let right = s.count - 1
    var temp = ""
    var ans = ""
    
    // Iterate the string and keep on adding to form a word to temp & transfer to ans
    // If empty space is encountered then add the current word to the ans
    while left <= right {
        let indexEl = s.index(s.startIndex, offsetBy: left)
        var ch = String(s[indexEl])
        if ch != " " {
            temp += ch// fill word into temp
        } else if ch == " " {// move data from temp to answer & reset temp
            if ans != "" {
                if temp != "" {// If contiguous element is " " empty string don't add any more white space
                    ans = temp + " " + ans
                }
            } else {
                ans = temp
            }
            temp = ""
        }
        left+=1
    }
    
    //If temp is not empty string then add to the result(Last word to be added)
    if temp != "" {
        if ans != "" {
            ans = temp + " " + ans
        } else {
            ans = temp
        }
    }
    
    return ans
}

let stringToReverseWords = "  My     Name    is Janesh"
let opWords =  reverseWords(stringToReverseWords)
print("op words--->", opWords, opWords.count)//op words---> Janesh is Name My 17

Leave a Comment

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