58. Length of Last Word
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
題意:
根據給定的字符串(包括大小寫的字母和空格),返回最後一個單詞的長度。如果最後一個單詞不存在,返回零。(自己加:如果最後的一個是空格,返回前一個單詞長度即可)
解題:
1)如果字符串爲空,返回零。
2)獲取字符串的長度,開始逐個讀取字符串。如果碰到的是字母,那麼size加一,登記單詞長度;如果碰到是空格,置size爲零,代表新單詞重新開始計數。
3)如果最後一個爲空格,那個置size爲零前保留值在prev中。只有在size不爲零的情況下才會把size保留在prev中,否則出現連續兩個空格的情況,會把prev置爲零的。
int lengthOfLastWord(char* s) { if ( !s ) { return 0; } int len = strlen( s ); int cnt = 0; int size = 0; int prev = 0; for ( cnt = 0; cnt < len; cnt++ ) { if ( *( s + cnt ) == ' ' ) { if ( size ) { prev = size; } size = 0; } else { size += 1; } } return size == 0 ? prev : size; }