代码随想录算法训练营Day9 | 151.翻转字符串里的单词 卡码网:55.右旋转字符串 28. 实现 strStr() - KMP

Day9

今天速刷三题,KMP还是挺难

151. Reverse Words in a String

其实不用这么麻烦,但我突发奇想了用这个思路继续往下写了。

class Solution {
public:
    string reverseWords(string s) {
        reverse(s.begin(), s.end());
        // cout << s;
        int idx = 0;
        string ans = "";
        string stack_str = "";
        while(idx < s.length())
        {
            if(s[idx] == ' ' && stack_str != "")
            {
                reverse(stack_str.begin(), stack_str.end());
                ans += stack_str;
                ans += " ";
                stack_str = "";
                cout << ans << "\n";
                while(s[idx] == ' ')
                    ++idx;
            }
            else
            {
                if(s[idx] != ' ')
                {
                    stack_str += s[idx];
                }
                ++idx;
            }
        }
        reverse(stack_str.begin(), stack_str.end());
        ans += stack_str;
        if(ans[ans.length()-1] == ' ')
            return ans.substr(0, ans.length()-1);
        return ans;
    }
};

卡码网:55.右旋转字符串

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int k;
    string str;
    cin >> k >> str;
    
    k = k % str.length();
    string s1 = str.substr(str.length()-k, k);
    string s2 = str.substr(0, str.length()-k);
    cout << s1 + s2;
    return 0;
}

28. Find the Index of the First Occurrence in a String

依旧难的KMP

class Solution {
public:
    void getNext(int* next, string& s) {
        int i=0;
        next[0] = 0;

        for(int j=1; j<s.length(); ++j) {
            while(i>0 && s[i] != s[j]) {
                i = next[i-1];
            }
            if(s[i] == s[j]){
                ++i;
            }
            next[j] = i;
        }
    }

    int strStr(string haystack, string needle) {
        if(needle.length() > haystack.length()) {
            return -1;
        }
        vector<int> next(needle.length());
        getNext(&next[0], needle);
        int j=0;
        for(int i=0; i<haystack.length(); ++i) {
            while(j>0 && haystack[i] != needle[j]) {
                j = next[j-1];
            }
            if(haystack[i] == needle[j]) {
                ++j;
            }
            if(j == needle.length()) {
                return (i - needle.length() + 1);
            }
        }
        return -1;
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值