您的位置:首页 > 其它

LeetCode(57)LengthOfLastWord

2014-01-22 16:58 211 查看
题目如下:

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.

分析如下:

本题完全没有涉及算法,考查的是编码时候考虑edge cases and corner cases的能力。主要分成四种情况

case 1: "AAAAAAAAAA" 整个输入字符串全部都是一个单词。

case 2: " " 整个输入字符串全部都是一堆空格。

case 4: "ABC DEF " 整个输入字符串有单词有空格,结尾是空格。

case 3: "ABC DEF" 整个输入字符串有单词有空格,结尾是单词。

我的代码:

// 12ms过大集合
int lengthOfLastWord(const char *s) {
        if(s==NULL)
            return 0;
        int i=0;
        int pos_space=-1;
        int pos_chara=-1;
        while(s[i]!='\0'){
            if(s[i]==' ')
                pos_space=i;
            else
                pos_chara=i;
            i++;
        }
        if(pos_space==-1) //case1
            return i;
        if(pos_chara==-1) //case2
            return 0;
        if(pos_space<pos_chara) //case3
            return pos_chara-pos_space;
        else{   //case4
            int length=0;
            while(s[pos_chara]!=' '&&pos_chara>=0){
                length++;
                pos_chara--;
            }
            return length;
        }
 }


尝试了一下,好不容易在非IDE的环境中写出了bug free的代码,太不容易了。

小结扩展1:

糖狗讲过的一道相关的面试题,给定一个输入,是一个句子,句子中有单词也有空格。要求把输出如下内容,把每个单词内部的字母的顺序逆序,但是句子中的单词的顺序不逆序。比如输入“This is tea.” 输出应当为 “sihT si aet.”。和上面的题不能说很像,但是有相关的地方在于也需要找到单词的界限。第一个单词的第一个字母必然为第一次出现的非空格字母,假设位置为a, 第一个单词的最后一个字母必然为a之后第一次出现的空格的位置,假设为b, 所以第一个单词被一个左开右闭的区间表达了出来[a, b),以此类推,代码如下。

void resverse_words_in_sentence(char *s) {
        if(s==NULL)
            return;
        int start=0;
        int end=0;
        while(s[start]==' ')
            start++;
        end=start;
        while(s[start]!='\0'&&s[end]!='\0'){
            while(s[end]!=' '&&s[end]!='\0')
                end++;
            int tmp_start=start;
            int tmp_end=end-1;
            while(tmp_start<tmp_end){
                char tmp=s[tmp_start];
                s[tmp_start]=s[tmp_end];
                s[tmp_end]=tmp;
                tmp_start++;
                tmp_end--;
            }
            start=end;
            while(s[start]==' '&&s[start]!='\0')
                  start++;
            end=start;
        }
}


小结扩展2:

Given a string , " This is a test" reverse it: " tset a si siht" Do this recursively. 来自于这里 。要求使用递归来解答。这段代码挺有意思的,简洁地表达了递归的力量。

//递归版反转一个字符串
void reverse_a_string(char* str){
    if(*str=='\0')
        return;
    reverse_a_string(str+1);
    std::cout<<*str;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: