【LeetCode算法-58/66】Length of Last Word/Plus One

LeetCode第58题:

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5

翻译:

获取最后一个单词的长度

思路:

思路很简单,要注意一点就是一些特殊情况,比如全是空格、或者只有一个单词

代码:

复制代码
class Solution {
    public int lengthOfLastWord(String s) {
        s = s.trim();
        if(s.length() == 0 ){
            return 0;
        }
        if(s.length() == 1){
            return 1;
        }
        return s.length() - 1 -s.lastIndexOf(" ");
    }
}
复制代码

 

LeetCode第66题:

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

翻译:

说了一大推,其实就是数组最后一个数字加1,但是数组的每个数字必须是个位数

思路:

其实就是整数的加法逻辑,现在改成数组,把其中的逻辑写出来而已。必须注意的是9加1等于10,要进一位

代码:

复制代码
class Solution {
    public int[] plusOne(int[] digits) {
        int length = digits.length;
        digits[length - 1] += 1;
        for(int i = length -1 ;i>=0;i--){
            if(digits[i] == 10){
                digits[i] = 0;
                if(i!=0){
                    digits[i - 1] +=1;
                }else{
            //新建一个数组
int[] result = new int[length+1]; result[0] = 1; for(int j = 1;j<result.length;j++){ result[j] = digits[j-1]; } return result; } } } return digits; } }
复制代码

欢迎关注我的微信公众号:安卓圈

posted @   嘉禾世兴  阅读(197)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2017-05-24 handler机制
点击右上角即可分享
微信分享提示