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

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

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

输入流解法

思路:遍历读取一个个字符,遇到空格重新计算长度
优点:速度快,占用空间少
时间复杂度:O(n)
来源:排行榜时间最少解法

public class Main {
    public static void main(String[] args) throws IOException{
        InputStream is = System.in;
        char c;
        int len = 0;
        while((c = (char)is.read()) != '\n'){
            len ++;
            if(c == ' '){
                len = 0;
            }
        }
        System.out.print(len);
    }
}
题解解法1

思路:使用Scanner,读取整行,然后从末尾开始找到空格结束
优点:未使用String内置split方法
时间复杂度:O(length)
来源:题解里面的解法

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int len = 0;
        for(int i = str.length() - 1; i >= 0 ; i--){
            if(' ' == str.charAt(i)){
                break;
            }
            len ++;
        }
        System.out.print(len);
    }
}
题解解法2

思路:使用Scanner,读取整行,然后把字符串拆分为数组,取最后一个
优点:简单,代码量少
缺点:使用了内置方法
时间复杂度:O(1)
来源:题解里面的解法

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String[] strArr = str.split(" ");
        System.out.println(strArr[strArr.length - 1].length());
    }
}
自己解法

思路:使用Scanner,读取每个单词,读到没有了结束
优点:理解简单
缺点:执行时间长,占用空间大,在idea里面好像没法跳出while
时间复杂度:O(n)
来源:题解里面的解法

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String a = "";
        while (in.hasNext()) {
            a = in.next();
        }
        System.out.println(a.length());
    }
}
#字符串最后一个单词的长度#
全部评论

相关推荐

喜欢喜欢喜欢:这是我见过最长最臭的简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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