1. 程式人生 > >leetcode (Number of Segments in a String)

leetcode (Number of Segments in a String)

Title:Number of Segments in a String   434

Difficulty:Easy

原題leetcode地址:https://leetcode.com/problems/number-of-segments-in-a-string/

 

1.    註解見程式碼註釋

時間複雜度:O(n),一次一層for迴圈,最長遍歷整個字串。

空間複雜度:O(1),沒有申請額外空間。

    /**
     * 當前字元為為“空”,且前一個字元為“空”,注意第一個字元
     * @param s
     * @return
     */
    public static int countSegments(String s) {

        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            if ((i == 0 || s.charAt(i - 1) == ' ') && s.charAt(i) != ' ') {
                count++;
            }
        }

        return count;

    }