If it’s empty, it indicates that this is the last word we need to print, and hence, there shouldn’t be any space after this word.We check if our answer variable is empty or not.It indicates that we have gone past a word and now we need to store it. We start traversing the string from the end until we hit a space. Can we somehow not use it and reverse the words as we move through the string? Could we store a word in reverse order when we are adding it to our answer variable? Approach: Intuition: Notice, that we are using a stack in order to perform our task. Space Complexity: O(N), Stack and ans variable Solution 2(Optimized Solution) Time Complexity: O(N), Traversing the entire string ("After reversing words: ") Īns += st.peek() // The last word should'nt have a space after it String s = "TUF is great for interview preparation"
0 Comments
Leave a Reply. |