From 32f0b8678d692db089bcaf236f21fe96d1ccb458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Tue, 9 Oct 2018 09:23:16 +0800 Subject: [PATCH] Create 434. Number of Segments in a String.md --- 434. Number of Segments in a String.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 434. Number of Segments in a String.md diff --git a/434. Number of Segments in a String.md b/434. Number of Segments in a String.md new file mode 100644 index 0000000..92ce97d --- /dev/null +++ b/434. Number of Segments in a String.md @@ -0,0 +1,21 @@ +# [434. Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/) +# 思路 +计算一个字符串被空格分成了多少部分。 +从头至尾遍历字符串,用tag标记当前字符的前一个字符是否是空格,若tag=1则前面是空格否则不是。若当前字符不是空格且tag==1则count应该加1。 +# C++ +``` +class Solution { +public: + int countSegments(string s) { + int tag = 1, res = 0; + for(int p = 0; p < s.size(); p++){ + if(s[p] == ' ') tag = 1; + else if(tag == 1){ // 当前字符不是空格且tag==1 + res++; + tag = 0; + } + } + return res; + } +}; +```