2017年12月18日 星期一

[LeetCode] 434. Number of Segments in a String

轉自LeetCode

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
code 如下

C++
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

Java可以使用 split 這個函數,但要注意的是,如果 input 是 "",  split 過後也還是回傳 ""

class Solution {
public int countSegments(String s) {
String trimmedStr = s.trim();
return (trimmedStr.equals("")) ? 0 : trimmedStr.split("\\s+").length;
}
}

沒有留言:

張貼留言