首页 > 试题广场 >

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

[编程题]字符串最后一个单词的长度
  • 热度指数:14039 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给出一个只包含大小写字母和空格的字符串s,请返回字符串中最后一个单词的长度
如果字符串中没有最后一个单词,则返回0
注意:单词的定义是仅由非空格字符组成的字符序列。
例如:
s ="Hello World",
返回5。
public class Solution {
    public int lengthOfLastWord(String s) {
        
        String[] ss = s.split("\\s");
        if (ss.length == 0)
            return 0;
        
        return ss[ss.length-1].length();
    }
}

发表于 2016-09-16 21:42:50 回复(0)

Java Solution

将字符串按空格分割,返回最后一个单词长度即可。

public class Solution {
    public int lengthOfLastWord(String s) {
        String[] res = s.split(" ");
        if (res.length > 0)
            return res[res.length - 1].length();
        return 0;
    }
}
发表于 2018-07-04 10:27:09 回复(0)
    int lengthOfLastWord(const char* s) {
        if(strlen(s) < 1) return 0;
        int count = 0, tail = strlen(s) - 1;
        //考虑末尾是空格的情况,遍历到第一个不是空格的字符为真正的末尾
        while(tail >= 0 && s[tail] == ' ') tail--;
        while(tail >= 0 && s[tail] != ' '){
            count++;
            tail--;
        }
        return count;
    }

发表于 2019-04-30 21:27:41 回复(0)
解法一:

class Solution {
    public int lengthOfLastWord(String s) {
       String[] array = s.trim().split("\\s+");
        return array[array.length - 1].length();
    }
}


解法二:
public int lengthOfLastWord(String s) {
        if (s == null | s.isEmpty()) return 0;

      
        int begin = 0, end = s.length();
        while (end > 0 && s.charAt(end - 1) == ' ') {
            end--;
        }
      
        for (int i = 0; i < end; i++) {
            if (s.charAt(i) == ' ') {
                begin = i + 1;
            }
        }

        return end - begin;
    }

解法三:

public int lengthOfLastWord(String s) {

        int count = 0;
        for (int i = s.length() - 1; i >= 0; i--) {

            if (s.charAt(i) == ' ') {
                if (count > 0) {
                    break;
                }
            } else {
                count++;
            }
        }
        return count;
    }



编辑于 2018-12-16 15:43:14 回复(0)
break , continue的典型用法
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int len = strlen(s);
        int count = 0;
        if(len == 0)
            return 0;
        for(int i = len - 1; i >= 0;i--){
            if(s[i] == ' ' && count)    // 出现空格,而且count不为零
                break;
            if(s[i] == ' ')
                continue;
            count += 1;
        }
        return count;
    }
};


发表于 2018-10-02 14:00:16 回复(0)
public class Solution {
    public int lengthOfLastWord(String s) {
    if (s == null || s.equals("")) {
      return 0;
    }

    int len = s.length();
    int end = len - 1;
    while (s.charAt(end) == ' ' && end > 0) {
      end--;
    }

    int start = end;
    while (start >= 0 && s.charAt(start) != ' ') {
      start--;
    }

    return end - start;
    }
}

发表于 2018-01-30 23:01:16 回复(0)
public class Solution {
    public int lengthOfLastWord(String s) {
        if (s==null||s.length()==0)
            return 0;
        int index=s.length()-1;
        while (s.charAt(index)==' '&&index>0){
            index--;
        }
        int start=index;
        while (index>=0&&s.charAt(index)!=' '){
            index--;
        }
        return start-index;
    }
}

发表于 2017-11-22 19:36:50 回复(0)
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int l = strlen(s);
        int k = 0;
        for(int i = l-1;i>=0;i--)
        {
            if(s[i] == ' ')
            {
                if(k)
                    break;             }else
                k++;         }         return k;
    }
};

发表于 2017-09-18 04:29:46 回复(0)
/*
	 * A single line of Code in Java
	 */
	public int lengthOfLastWord(String s) {
		return s.trim().length() - s.trim().lastIndexOf(" ") - 1;
	}

发表于 2017-07-21 11:02:40 回复(1)

I've noticed that a lot of solutions use available library functions that return directly the positions of certain characters or do other operations like "split". I personally don't think that's a good idea. Firstly, these functions take some time and usually involve with iteration through the whole string. Secondly, questions like this one is intended to be a practice of detail implementation, not calling other functions. My solution like below uses only the most basic string operations and probably beats many other solutions which call other existing functions.

int lengthOfLastWord(const char* s) { int len = 0;
        while (*s) { if (*s++ != ' ')
                ++len; else if (*s && *s != ' ') len = 0;
    
        } return len;
    }
发表于 2017-03-12 12:32:39 回复(0)
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int count = 0;
        int len = strlen(s);
//反向查找,末尾空格忽略,行中出现空格就终止循环
        for(int i = len-1; i >= 0 ; i--){
            if(s[i] == ' '){
                if(count)
                    break;
            }
            else{
                count++;
            }
        }
        return count;
    }
};

编辑于 2017-03-08 10:09:13 回复(0)
//利用C++的输入输出控制类 stringstream
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        stringstream ss(s);
        string str;
        while(ss >> str);
        return str.length();
    }
};

发表于 2016-04-17 11:21:33 回复(3)
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        //反向查找
        int count=0;
        int l=strlen(s);
        for(int i=l-1;i>=0;i--){
            if(s[i]==' '){
                if(count)
                    break;
            }
            else
                count++;
        }
        return count;
    }
};
发表于 2021-10-27 16:02:23 回复(0)
用strlend的都是不合格的😀
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        if(s == NULL || s[0] == '\0') return 0;
        int len = 0;
        const char *pos1 = s;
        while(*pos1 == ' ') pos1++;
        const char *pos2 = pos1;
        while(*pos1 != '\0') {
            if(*pos1 == ' ') {
                len = pos1 - pos2;
                while(*pos1 == ' ') ++pos1;
                pos2 = pos1;
                if(*pos1 == '\0') break;
            }
            pos1++;
        }
        if(pos2 != pos1) len = pos1 - pos2;
        return len;
    }
};


发表于 2020-11-10 11:41:20 回复(0)
String的index()和lastIndexOf()方法真的很好用。
public class Solution {
    public int lengthOfLastWord(String s) {
        if(s==null||s.length()==0){
            return 0;
        }
        s=s.trim();
        if(s.indexOf(" ")==-1){
            return s.length();
        }else{
            return s.length()-s.lastIndexOf(" ")-1;
        }
    }
}


发表于 2020-11-04 17:07:35 回复(0)

基本思路:遍历字符串,用start指针指向单词开头,end指针指向单词结尾,如果有单词,end-start+1即为最后一个单词的长度。

代码如下:

//
// Created by jt on 2020/9/29.
//
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        if (!s) return 0;
        // 找到最后一个空格
        const char *p = s, *start = nullptr, *end = nullptr;
        while (*p) {
            // 如果当前位置非空格且当前位置为起始位置,或当前位置非空格且前面位置为空格,保存单词的头指针
            if ((*p != ' ' && p == s ) || (*p != ' ' && *(p-1) == ' ')) start = p;
            // 如果当前位置非空格,后面位置为结尾或空格,保存单词的尾指针
            if (*p != ' ' && (*(p+1) == '\0' || *(p+1) == ' ')) end = p;
            ++p;
        }
        if (start == nullptr || end == nullptr) return 0;
        else return end - start + 1;
    }
};
发表于 2020-09-29 11:45:17 回复(0)
  public int lengthOfLastWord(String s) {
      /**String[] res = s.split(" ");
        if (res.length > 0)
            return res[res.length - 1].length();
        return 0;*/
        if (s == null || s.length() == 0){
            return 0;
        }
        int count = 0;
        for (int i = s.length() -1; i >=0; i--) {
            //
            if (s.charAt(i) != ' '){
                count++;
            }else if (count != 0){//找到最后一个单词前面的空格
                break;
            }
        }
        return count;
    }

编辑于 2020-08-25 19:53:15 回复(0)
public class Solution {
    public int lengthOfLastWord(String s) {
        int res = 0;
        int i = s.length()-1;
        while(i>=0 && s.charAt(i)==' ')
            i--;
        while(i>=0 && s.charAt(i)!=' '){
            i--;
            res++;
        }
        return res;
    }
}

发表于 2020-04-25 10:34:46 回复(0)
public class Solution {
    public int lengthOfLastWord(String s) {
        if (s == null)
            return 0;
        
        s = s.trim();
        if (s.length() == 0)
            return 0;
            
        int cnt = 0, index = s.length() - 1;
        
        while (index >= 0 && s.charAt(index) != ' ') {
            cnt++;
            index--;
        }
        
        return cnt;
    }
}
发表于 2020-04-05 16:44:23 回复(0)
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int n = strlen(s);
        int lastSize = 0;
        bool letterSeen = false;
        while (--n >= 0) {
            if (s[n] == ' ' && letterSeen) {
                break;
            }
            if (s[n] != ' ') {
                lastSize++;
                letterSeen = true;
            }
        }
        return lastSize;
    }
};

发表于 2019-11-21 23:57:45 回复(0)

问题信息

难度:
59条回答 15625浏览

热门推荐

通过挑战的用户

查看代码