leetcode -- 434. Number of Segments in a String 【字符串处理】
来源:互联网 发布:文娱小说推荐知乎 编辑:程序博客网 时间:2024/05/20 02:28
题目
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
题意
给定一个字符串,计算片段的数量。一个片段定义为连续的没有空格的字母序列。
分析及解答
解答1:(击败 %78)
public static int countSegments(String s) { char[] array = s.toCharArray(); int len = array.length; boolean isPreSpace = true; boolean isCurrentSpace = true; int count= 0; for(int i = 0; i <len ;i++){ isCurrentSpace = (array[i] == ' '); if(isPreSpace){ if(isCurrentSpace){ isPreSpace = true; }else{ isPreSpace = false; count++; } }else{ isPreSpace = isCurrentSpace; } } return count; }
解答2:(击败 3%)(反面教材)
- 利用了正则表达式。(较为消耗时间)
public int countSegments(String s) { if(s.equals("")) return 0; String[] results = s.split("\\s+"); if(results == null || results.length == 0) return 0; if(results[0].equals("")){ return results.length -1; } return results.length; }
阅读全文
0 0
- 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 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 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
- 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]434. Number of Segments in a String
- 什么是字符集
- 最长公共子序列Lcs
- 利用IO流文实现对件夹的拷贝(文本)
- Wireless Network
- 1053. Path of Equal Weight (30)
- leetcode -- 434. Number of Segments in a String 【字符串处理】
- TCP/IP 详解卷一学习笔记(六):TCP 超时与重传
- 产品经理必知的10种数据分析方法
- HDU
- Boredom (DP)
- 阿里云服务器CentOS6.8搭建SVN服务器
- 机器学习都有哪些style?
- UVA-455Periodic Strings
- java语言特点