【LC刷题】DAY08:151 55 28 459

作者 : admin 本文共1503个字,预计阅读时间需要4分钟 发布时间: 2024-06-16 共1人阅读

【LC刷题】DAY08:151 55 28 459

文章目录

  • 【LC刷题】DAY08:151 55 28 459
    • 151. 反转字符串中的单词 [link](https://leetcode.cn/problems/reverse-words-in-a-string/description/)
    • 55. 右旋字符串 [link](https://kamacoder.com/problempage.php?pid=1065)
    • 28. 找出字符串中第一个匹配项的下标 [link](https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/)
    • 459. 重复的子字符串[link](https://leetcode.cn/problems/repeated-substring-pattern/description/)

151. 反转字符串中的单词 link

class Solution {
public:
    string reverseWords(string s) {
        vector ss;
        string tmp = "";
        for (char t : s) {
            if (t != ' ') {
                tmp += t;
            } else if (!tmp.empty()) { // 使用empty检查字符串是否为空
                ss.insert(ss.begin(), tmp);
                tmp = "";
            }
        }
        // 确保最后一个单词也被添加
        if (!tmp.empty()) {
            ss.insert(ss.begin(), tmp);
        }

        string result;
        for (const string& t : ss) {
            result += t;
            result += " "; // 将空格添加到每个单词后面,除了最后一个
        }
        // 移除末尾多余的空格
        if (!result.empty()) {
            result.pop_back();
        }
        return result;
    }
};

55. 右旋字符串 link

#include 
#include 
using namespace std;

int main(){
    string s = "";
    int k;
    cin>>k;
    cin>>s;
    
    string result = "";
    for(int i = s.size()  - k; i < s.size() ; i ++ ){
        result += s[i];
    }
    for(int i = 0 ; i < s.size() - k; i++){
        result += s[i];
    }
    cout << result;
    return 0;
}

28. 找出字符串中第一个匹配项的下标 link

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size(), m = needle.size();
        for (int i = 0; i + m <= n; i++) {
            bool flag = true;
            for (int j = 0; j < m; j++) {
                if (haystack[i + j] != needle[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;
    }
};

459. 重复的子字符串link

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int n = s.size();
        for(int i = 1; 2 * i <= n; i++){
            if(n % i == 0 ){
                bool match = true;
                for(int j = i ; j < n; j ++){
                    if(s[j] != s[j-i]){
                        match = false;
                        break;
                    }
                }
                if(match){
                    return true;
                }
            }
        }
        return false;
    }
};
本站无任何商业行为
个人在线分享 » 【LC刷题】DAY08:151 55 28 459
E-->