adding string iterator problem

This commit is contained in:
Jidong Xiao
2023-09-29 11:26:46 -04:00
parent 927fa8cb04
commit 98c3e19192
2 changed files with 34 additions and 1 deletions

View File

@@ -162,4 +162,5 @@ also defined.
## 9.9 Leetcode Exercises ## 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 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)

View File

@@ -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<string> 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();
}
};