您的位置:首页 > 其它

今日LeetCode--28,38

2017-05-15 15:03 411 查看
28. Implement strStr()

代码如下:

class Solution {

public:

    int strStr(string haystack, string needle) {

        int offset;

        int h = haystack.length();

        int n = needle.length();

        int i;

        if(n==0)

            return 0;

        if(h==0)

            return -1;

        for(i = 0; i< h-n+1; i++){

            for(offset = 0; offset < n; ){

                if(haystack[i+offset]==needle[offset])

                    offset++;

                else

                    break;

            }

            if(offset == n)

                return i;

             

        }

        if(offset == n)

            return i;

        else  

            return -1;

         

    }

};

还可以用flag;

还可以用KMP, 以后有时间再尝试;

//for(offset = 0; offset < n; ){

曾出错;

38. count and say

第一次尝试递归,有时间尝试一下非递归。

代码如下:

 string countAndSay(int n) {

        if(n == 1)

            return "1";

        if(n == 2)

            return "11";

        string res = "";

        //int i;

        string res_tmp = countAndSay(n-1);

        int count = 1;

        int length = res_tmp.length();

        for(int i = 1; i < length ; i++){

            if(res_tmp[i] == res_tmp[i-1]){

                count++;

            }

            else{

                res.push_back('0'+count);

                res.push_back(res_tmp[i-1]);

                count = 1;

            }

            if(i == length-1){

                res.push_back('0'+count);

                res.push_back(res_tmp[i]);

            }

                 

        }

        return res;

         

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: