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

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

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

思路

我本来想到的解法是倒置数组,然后遍历,每遍历一个字符,计数器加1,直到遇到空格,循环退出。

实际上我的Java代码就是这么写的:

import java.util.Scanner;

public class Main {

    public int convert(String str) {
        char[] chars = str.toCharArray();
        int length = 0;
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] == ' ') {
                break;
            }
            length++;
        }
        return length;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Main main = new Main();
        while (in.hasNext()) {
            String str = in.nextLine();
            System.out.println(main.convert(str));
        }
    }
}

这种算法也不赖。

还有一种解法,就是我正序遍历字符串,每次计数器加1,遇到空格置0,那么最后一个单词的长度就能统计出来了:

#include <stdio.h>

int main() {
    char str[5000];
    int i = 0;
    int count = 0;
    while (scanf("%c", &str[i]) != EOF)
    {
        if (str[i] == ' ')
        {
            count = 0;
        }
        else
        {
            count += 1;
        }
    }
    printf("%d\n", count-1);
    return 0;
}

当然了,我还是最倾向于我自己最开始想出来的算法,从后往前遍历:

#include <stdio.h>
#include <string.h>

#define SIZE 5000

int main() {
    char array[SIZE];
    gets(array);
    int count = 0;
    int len = strlen(array);
    for (int i = len - 1; i >= 0; i--)
    {
        if (array[i] == ' ')
        {
            break;
        }
        count += 1;
    }
    printf("%d\n", count);
    return 0;
}

最近在学C++,于是写个C++版本的:

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

int main() {
    string str;
    getline(cin, str);

    int count = 0;
    int len = str.length();
    for (int i = len - 1; i >= 0; i--)
    {
        if (str[i] != ' ')
        {
            break;
        }
        count += 1;
    }
    cout << count << endl;
    return 0;
}
全部评论

相关推荐

钱嘛数字而已:辅导员肯定不能同意,不然你出事了,他要承担责任。但是,脚和脑子都长在你自己身上,使用它还需要向辅导员报告么? 辅导员必须按流程拒绝你,然后你拿出成年人的态度,做自己的选择。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务