adding string iterator problem
This commit is contained in:
@@ -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)
|
||||
|
||||
32
leetcode/p58_lengthoflastword.cpp
Normal file
32
leetcode/p58_lengthoflastword.cpp
Normal 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();
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user