【LeetCode】Number of Segments in a String 解题报告
来源:互联网 发布:淘宝天机充值平台 编辑:程序博客网 时间:2024/06/07 16:36
【LeetCode】Number of Segments in a String 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/number-of-segments-in-a-string/#/description
题目描述:
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
Ways
这个题方法应该自己使用过的,不过是倒着来。回想自己以前在每个单词后面输入一个空格,但是行尾不要空格的时候怎么做的?不就是判断第一个单词的前面不打空格,在之后的所有单词的前面打了一个空格。这个题的思路是不是倒着来?
判断某个单词的开始的字符前面是不是空格,如果是字符串的第一个字符也会把技术加1,这样就能统计出所有用空格分割的字符串段的个数。
public class Solution { public int countSegments(String s) { int count = 0; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')){ count++; } } return count; }}
方法二:使用正则表达式。正则\s
表示匹配空格,+
表示匹配一次或者任意多次。所以有以下代码。
public int countSegments(String s) { String trimmed = s.trim(); if (trimmed.length() == 0) return 0; else return trimmed.split("\\s+").length;}
Date
2017 年 5 月 5 日
0 0
- 【LeetCode】Number of Segments in a String 解题报告
- [Leetcode] 434. Number of Segments in a String 解题报告
- Leetcode 434. Number of Segments in a String 字符串的分段 解题报告
- Leetcode Number of Segments in a String
- LEETCODE--Number of Segments in a String
- LeetCode 434. Number of Segments in a String
- Leetcode 434 Number of Segments in a String
- Leetcode Number of Segments in a String 434
- LeetCode 434. Number of Segments in a String
- 【Leetcode 434. Number of Segments in a String】
- leetcode 434. Number of Segments in a String
- LeetCode 434. Number of Segments in a String
- leetcode oj java Number of Segments in a String
- LeetCode 434. Number of Segments in a String
- Leetcode 434. Number of Segments in a String (Easy) (cpp)
- 【LeetCode】 434. Number of Segments in a String
- [leetcode]434. Number of Segments in a String
- [leetcode]434. Number of Segments in a String
- 深入PHP面向对象、模式与实践——企业模式(2)
- Android 辅助面试题一
- java 中重写toString()方法
- jxl 读写Excel实例(設置cell format 格式)
- js控制上传文件大小
- 【LeetCode】Number of Segments in a String 解题报告
- Hadoop入门基础教程 Hadoop之单词计数
- HTML5复习 (15)
- [转]VS2015代码自动对齐
- 获取并配置对 AD FS 令牌签名证书和令牌解密证书
- Install GraphicsMagick on Linux
- Class.getResource VS ClassLoader.getResource
- android view绘制过程
- [学习]C++ STL(自定义泛型算法)