ファーウェイマシン-文字列の最後の単語の長さ


タイトルの説明
文字列の最後の単語の長さを計算し、単語はスペースで区切られます.
じこかい
考え方:左から右に検索し、getline()は行全体の入力を読み込み、文字ループは、スペースカウントに遭遇するたびにゼロに戻り、最後のスペースまでの文字カウントが結果となります.
#include 
using namespace std;
int main()
{
    string str;
    while(getline(cin, str))
    {
        int i = 0;
        int count = 0;
        while(str[i] != '\0')
        {
            if(str[i] != ' ')
            {
                count++;
            }
            else
            {
                count = 0;
            }
            ++i;
        }
        cout << count << endl;
    }
    return 0;
}

運転時間:6 msサイズ:616 K
その他
考え方:右から左に検索し、スペースカウントが終了すると結果が得られます.
#include 
#include 
using namespace std;
  
class Solution 
{
public:
    int CountWordLen(string str) 
    {
        int len = str.size();
        if(len == 0) 
        {
        	return 0;
        }
        int count = 0;
        for(int i = len-1; i>=0 && str[i] != ' '; i--) 
        {
            count++;
        }
        return count;
    }
};
  
int main() 
{
    Solution S;
    string str;
    while(getline(cin,str)) 
    {
        cout << S.CountWordLen(str) << endl;
    }
    return 0;
}

速度:18 msサイズ:596 K