leetcode上开了《剑指offer》专栏,深夜回家特来水一下。题解后续补上~
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Solution { private: void reverse(string &s, unsigned int left, unsigned int right) { unsigned int i; char x; for (i = left; i <= (left + right) / 2; i++) { x = s[i]; s[i] = s[right - i + left]; s[right - i + left] = x; } } public: string reverseLeftWords(string s, int n) { reverse(s, 0, n - 1); reverse(s, n, s.size() - 1); reverse(s, 0, s.size() - 1); return s; } }; |
单元测试案例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <gtest/gtest.h> TEST(Solution, leetcode_1) { Solution s; string str = "abcdefg"; //"cdefgab"; EXPECT_EQ(s.reverseLeftWords(str, 2), "cdefgab"); } TEST(Solution, leetcode_2) { Solution s; string str = "lrloseumgh"; //"umghlrlose"; EXPECT_EQ(s.reverseLeftWords(str, 6), "umghlrlose"); } int main() { ::testing::InitGoogleTest(); return RUN_ALL_TESTS(); } |
评论