TreeviewCopyright © aleen42 all right reserved, powered by aleen42

434. 字符串中的单词数

https://leetcode-cn.com/problems/number-of-segments-in-a-string/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-09 07:04:17
 * @LastEditTime: 2020-08-09 07:05:23
 * @Description: https://leetcode-cn.com/problems/number-of-segments-in-a-string/
 * @FilePath: \leetcode-googtech\#434. Number of Segments in a String\Solution.java
 */

class Solution {
    public int countSegments(String s) {
        // 将字符串转换为char数组
        char[] chars = s.toCharArray();
        int len = 0;
        char lastChar = ' ';
        // 遍历char数组并统计字符串中的空格数
        for(char c : chars) {
            if(c != ' ' && lastChar == ' ') {
                len++;
            }
            lastChar = c;
        }
        return len;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-08-09 07:04:25
LastEditTime: 2020-08-09 07:06:02
Description: https://leetcode-cn.com/problems/number-of-segments-in-a-string/
FilePath: \leetcode-googtech\#434. Number of Segments in a String\Solution.py
'''

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        length = 0
        lastChar = ' '
        # 循环遍历数组元素
        for c in s:
            # 统计字符串中的空格数
            if c != ' ' and lastChar == ' ':
                length += 1
            lastChar = c
        return length
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""