leetcode 【434】Number of Segments in a String
阿新 • • 發佈:2018-11-01
寫在最前面: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中的資料結構並不多,字典,列表,元組,用起來想清楚你在操作什麼型別的東東,就可以了
為什麼別人的部落格瀏覽量,粉絲,關注都那麼多。。。