LeetCode
来源:互联网 发布:伯明翰大学 知乎 编辑:程序博客网 时间:2024/06/05 00:32
题目:
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.
思路与步骤:
基本思路:
依次读入字符串中的字符,遇到字符跳过,直到空格,此时count+1;
细节处理:
当出现连续空格时,所以遇到空格要循环读直到空格结束,此时才count+1;
若开始就有空格,所以要先判断遇见的空格,若不再出现字符,则返回0;若出现了字符,则此后count才开始计数。
学习别人的思路:
循环中直接判断是否是字符,如果是,并且其前一个是空格,则count计数。
此时要注意,当字符串中只有一个有效字符时,“前一个”会造成数组下标异常,所以多一条判断,但是不用再 if 了,直接 i==0 || s.charAt(i-1)==' '即可。这里要注意,不能写成s.charAt(i-1)==' ' || i==0 .程序后面会详细解释。
编程实现:
我的解法:
public class Solution { public int countSegments(String s) { int count = 0; for(int i=0; i<s.length(); i++){ while(s.charAt(i) == ' ' && i<s.length()-1) i++; if(s.charAt(i) != ' '){ while(s.charAt(i) != ' ' && i<s.length()-1) i++; count++; } } return count; }}
别人的程序:
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++; //Notice: The following sentence - java.lang.StringIndexOutOfBoundsException: String index out of range: -1 //if(s.charAt(i)!=' ' && (s.charAt(i-1)==' ' || i==0)) count++; //Not AC } return count; }}
这里需要特别注意!
i==0 || s.charAt(i-1)==' ' 中 i==0 必须放在前面,否则先判断 s.charAt(i-1) 时会下标溢出!
(所以,机器也是很懒的,判断或语句时,前半截true 就不会再看后半截。。。)
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- h5 固定底部
- MIPI-DSI
- 题目1143:Primary Arithmetic
- AnnotationWorkflowInterceptor
- Hive扩展功能(九)--Hive的行级更新操作(Update)
- LeetCode
- mysql处理海量数据时的一些优化查询速度方法
- salesforce 零基础学习(六十六)VF页面应善于使用变量和函数(二)常用函数的使用
- 嵌入式下Qt背景隐藏
- Windows7下Python3.4使用MySQL数据库(安装教程)
- 360浏览器默认打开页面的方式(极速、IE)
- Fresco使用的一些坑(初学者)
- Lnmp mysql+php+nigx+discuz 续
- 阿里提示Discuz uc.key泄露导致代码注入漏洞的解决方法