541. 反转字符串 II
给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。
如果剩余字符少于 k 个,则将剩余字符全部反转。
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
示例 1:
输入:s = "abcdefg", k = 2
输出:"bacdfeg"
class Solution {
public:
string reverseString(string s, int left, int right){
if (right >= s.length()) right = s.length()-1;
while(left<right){
swap(s[left], s[right]);
++left; --right;
}
return s;
}
string reverseStr(string s, int k) {
int i = 0;
for (; i*k < s.length(); ++i){
if (i%2==0){
s = reverseString(s, i*k, (i+1)*k-1);
}
}
return s;
}
};
剑指 Offer 58 - II. 左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
class Solution {
public:
string reverseLeftWords(string s, int n) {
reverse(s.begin(), s.begin()+n);
reverse(s.begin()+n, s.end());
reverse(s.begin(), s.end());
return s;
}
};
28. 实现 strStr()
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
class Solution {
public:
//暴力
int strStr(string haystack, string needle) {
if (needle=="") return 0;
int start = 0;
for (int i = 0; i < haystack.length(); ++i){
if (haystack[i]==needle[start]){
while(start < needle.length() && haystack[i]==needle[start]){
++i; ++start;
}
if (start == needle.length()){
return i - start;
}else{
i = i - start;
start = 0;
}
}
}
return -1;
}
};
class Solution {
public:
void makeNext(string needle, vector<int>& next){
next.resize(needle.length(),0);
int j = 0;
for (int i = 1; i < needle.length(); ++i){
while(j > 0 && needle[i]!=needle[j]) j = next[j-1];
if (needle[i]==needle[j]) ++j;
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle == "") return 0;
vector<int> next;
makeNext(needle, next);
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;
}
};