左旋转字符串

This commit is contained in:
yaha 2023-05-25 10:20:40 +08:00
parent 59586d0eb6
commit 81da2f5b17
3 changed files with 45 additions and 14 deletions

View File

@ -35,6 +35,14 @@ public:
*/
bool is_number(std::string s);
/**
* Offer 58 - II.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/589fz2/
* @param s
* @param n
* @return
*/
std::string reverse_left_words(std::string s, int n);
};
@ -55,6 +63,16 @@ public:
void reverse_stack(ListNode *head, std::vector<int> &res);
void reverse(ListNode *head, std::vector<int> &res);
/**
* Offer 24.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/9pdjbm/
* @param head
* @return
*/
ListNode *reverse_list(ListNode *head);
ListNode* reverse_list(ListNode* cur, ListNode* pre);
};
@ -95,19 +113,6 @@ public:
private:
std::stack<int> _stk;
std::stack<int> _min_stk;
void reverse_stack(ListNode *head, std::vector<int> &res);
void reverse(ListNode *head, std::vector<int> &res);
/**
* Offer 24.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/9pdjbm/
* @param head
* @return
*/
ListNode *reverse_list(ListNode *head);
ListNode* reverse_list(ListNode* cur, ListNode* pre);
};
}

View File

@ -1,6 +1,25 @@
#include "jianzhi_offer.h"
namespace yaha {
std::string String::reverse_left_words(std::string s, int n) {
// 方法1 遍历
// std::string cur_str;
// std::string new_str;
// for (int i = 0; i < s.length(); ++i) {
// if (i < n) {
// cur_str += s[i];
// } else {
// new_str += s[i];
// }
// }
//
// return new_str + cur_str;
// 方法2 内置函数
return s.substr(n, s.size()) + s.substr(0, n);
}
std::string String::replace_space(std::string s) {
std::string result;
for (int i = 0; i < s.length(); ++i) {

View File

@ -17,3 +17,10 @@ TEST(IsNumberTest, BasicAssertions) {
ASSERT_FALSE(s.is_number("e"));
ASSERT_FALSE(s.is_number("e9"));
}
TEST(ReverseLeftWords, BasicAssertions) {
yaha::String s;
ASSERT_EQ("cdefgab", s.reverse_left_words("abcdefg", 2));
ASSERT_EQ("umghlrlose", s.reverse_left_words("lrloseumgh", 6));
}