leetcode 【434】Number of Segments in a String

版权声明:本文为博主原创文章,未经允许,不得转载,如需转载请注明出处 https://blog.csdn.net/ssjdoudou/article/details/83311866

写在最前面:null

leetcode 434 Number of Segments in a String

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: "Hello, my name is John"
Output: 5

统计连续的不是空格的字符

方法一:

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.split())

split函数用来删除字符串中指定字符,如果split(),就是去掉空格,,如果你尝试打印一下,会发现字符串被按照空格打散挨个输出了,输出类型是list,只要计算该list的长度,就能得到结果

方法二:

class Solution:
    def countSegments(self, s):
        number = 0
        length = len(s)
        print(length)
        if s == "":
            number = -1
        for i in range(0, length-1):
            if s[i] != " " and s[i+1] == " ":
                number += 1
        if length != 0 and s[length-1] == " ":
            number = number-1
        return number+1

基本思路是判断s[i]不为空,s[i+1]为空,那么就统计一个,因为考虑到最后一个不为空,所以返回加一,又考虑到如果最后一个为空,而整个字符串有单词,那么又不能加一,所以,这里for循环结束又对number做了一次处理,大家可以仔细琢磨一下,纯原创,非抄袭。

上一段java的,java我也会的,哼哼

package Arithmetic;

public class countsegments {

	public static void main(String[] args) {
		countsegments xxx =new countsegments();
		// TODO Auto-generated method stub
		String a = " aaa err";
		System.out.println(xxx.countSegments(a));

	}
	public int countSegments(String s) {
		if(s==null ||s.length()==0){
	            return 0;
	        }
	    int count=0;
		for(int i=0;i<s.length();i++) {
			if(s.charAt(i)==' ') {
				if(i<s.length()-1) {
					if(s.charAt(i+1)!=' ') {
						count++;
					}
				}
			}
		}
		if(s.charAt(0)==' ') {
			count--;
		}
		return count+1;
    }
}

写在最后:

python中的数据结构并不多,字典,列表,元组,用起来想清楚你在操作什么类型的东东,就可以了

为什么别人的博客浏览量,粉丝,关注都那么多。。。

猜你喜欢

转载自blog.csdn.net/ssjdoudou/article/details/83311866