If you want to know what words are in the string


  • 0
    C

    Here is my solution to this problem.
    I used istringstream in <sstream> to extract all words in the string and put them in a vector.
    My code works if the input string only includes A~Za~z and space.

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <algorithm>
    #include <iterator>
    using namespace std;
    class Solution {
    public:
    	int lengthOfLastWord(string s) {
    		istringstream iss(s);
    		vector<string> tokens{ istream_iterator<string>{iss},
    			istream_iterator<string>{} };
    		if (tokens.size() == 0) {
    			return 0;
    		}
    		return tokens[tokens.size() - 1].size();
    	}
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.