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.


思路與步驟:

基本思路:

依次讀入字符串中的字符,遇到字符跳過,直到空格,此時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 就不會再看後半截。。。)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章