本文主要是介绍【LC刷题】DAY08:151 55 28 459,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【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<string> 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 <iostream>
#include <cstring>
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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!