题解 | #字符串最后一个单词的长度#

字符串最后一个单词的长度

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da


#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int stringLength(string& s)
{
    int n = s.size();
    int tempCount = 0;
//优化后的代码
    size_t fountr = s.find(' ');
    if(fountr == string::npos)
    {
        return s.length();
    }
    size_t found = s.find_last_of(' ');
//     size_t found = s.rfind(' ');
    string resultS = s.substr(found+1);
    return resultS.size();
//优化前
//     for(int i = 0; i < n; i ++)
//     {
//         if(s[i] == ' ')
//         {
//             tempCount++;
//         }
//     }
//     vector<string> temp(s);
//     int num = s.count(s.begin(),s.end(),' ');
    
//     int stringCount = 0;
//     if(tempCount == 0)
//     {
//         return s.size()+1;
//     }
//     int count1 = 0;
//     for(int i = 0; i < n; i ++)
//     {
//         if(s[i] == ' ')
//         {
//             stringCount++;
//             if(stringCount == tempCount)
//             {
//                 for(int j = i; j < n; j++)
//                 {
//                     if(s[j] != '\0')
//                     {
//                         count1 ++;
//                     }
//                 }
//             }
//         }
//     }
//     return count1;
}

int main()
{
    string s;
    getline(cin,s);
    int count2 = stringLength(s);
    cout << count2 << endl;
    return 0;
}
#在线刷题#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务