diff --git a/include/jianzhi_offer.h b/include/jianzhi_offer.h index e9d3226..19a3f72 100644 --- a/include/jianzhi_offer.h +++ b/include/jianzhi_offer.h @@ -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 &res); void reverse(ListNode *head, std::vector &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 _stk; std::stack _min_stk; - - void reverse_stack(ListNode *head, std::vector &res); - void reverse(ListNode *head, std::vector &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); }; } \ No newline at end of file diff --git a/src/jianzhi_offer/string.cpp b/src/jianzhi_offer/string.cpp index e437620..8e87478 100644 --- a/src/jianzhi_offer/string.cpp +++ b/src/jianzhi_offer/string.cpp @@ -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) { diff --git a/tests/jianzhi_offer/string_test.cpp b/tests/jianzhi_offer/string_test.cpp index a5d7224..b89c9b7 100644 --- a/tests/jianzhi_offer/string_test.cpp +++ b/tests/jianzhi_offer/string_test.cpp @@ -16,4 +16,11 @@ TEST(IsNumberTest, BasicAssertions) { ASSERT_FALSE(s.is_number(".")); ASSERT_FALSE(s.is_number("e")); ASSERT_FALSE(s.is_number("e9")); -} \ No newline at end of file +} + +TEST(ReverseLeftWords, BasicAssertions) { + yaha::String s; + ASSERT_EQ("cdefgab", s.reverse_left_words("abcdefg", 2)); + ASSERT_EQ("umghlrlose", s.reverse_left_words("lrloseumgh", 6)); +} +