diff --git a/lectures/09_iterators_linked_lists/README.md b/lectures/09_iterators_linked_lists/README.md index d4ac39c..f35306a 100644 --- a/lectures/09_iterators_linked_lists/README.md +++ b/lectures/09_iterators_linked_lists/README.md @@ -162,4 +162,5 @@ also defined. ## 9.9 Leetcode Exercises - [Leetcode problem 27: Remove Element](https://leetcode.com/problems/remove-element/). Solution: [p27_removeelement.cpp](../../leetcode/p27_removeelement.cpp) -- [Leetcode problem 283: Remove Zeroes](https://leetcode.com/problems/move-zeroes/). Solution: [p283_movezeroes.cpp](../../leetcode/p283_movezeroes.cpp) +- [Leetcode problem 58: Length of Last Word](https://leetcode.com/problems/length-of-last-word/). Solution: [p58_lengthoflastword.cpp](../../leetcode/p58_lengthoflastword.cpp) +- [Leetcode problem 283: Move Zeroes](https://leetcode.com/problems/move-zeroes/). Solution: [p283_movezeroes.cpp](../../leetcode/p283_movezeroes.cpp) diff --git a/leetcode/p58_lengthoflastword.cpp b/leetcode/p58_lengthoflastword.cpp new file mode 100644 index 0000000..31e0268 --- /dev/null +++ b/leetcode/p58_lengthoflastword.cpp @@ -0,0 +1,32 @@ +// demonstration of using an iterator to traverse a string + +class Solution { +public: + int lengthOfLastWord(string s) { + string::iterator itr = s.begin(); + vector words; + string word = ""; + while(itr != s.end()){ + // skip leading spaces + while(itr != s.end() && *itr == ' '){ + itr++; + } + + // remember we still need to check whether itr reaches the end or not; if we don't check, we may get a stack buffer overflow issue. + while(itr != s.end() && *itr != ' '){ + // append this letter to the end of the word + word = word + *itr; + itr++; + } + // word is now complete, store it in words. + // caution: word may be empty because of the spaces at the end of s. + if(!word.empty()){ + words.push_back(word); + // reset word + word = ""; + } + } + word = words.back(); + return word.length(); + } +};