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<Solution>
想法如下
- 如果當下的字元不是空白,然後前一個字元是空白,代表就遇到一個 segment
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int countSegments(string s) { | |
int cnt = 0; | |
const int len = s.length(); | |
for(int i = 0; i < len; i++) { | |
if((i == 0 || s[i-1] == ' ') && s[i] != ' ') { | |
++cnt; | |
} | |
} | |
return cnt; | |
} | |
}; |
Java可以使用 split 這個函數,但要注意的是,如果 input 是 "", split 過後也還是回傳 ""
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int countSegments(String s) { | |
String trimmedStr = s.trim(); | |
return (trimmedStr.equals("")) ? 0 : trimmedStr.split("\\s+").length; | |
} | |
} |
沒有留言:
張貼留言