首页 > 其他 > 详细

LintCode: Rotate String

时间:2015-11-27 10:40:43      阅读:408      评论:0      收藏:0      [点我收藏+]

C++,

time: O(n)

space:O(n)

 1 class Solution {
 2 public:
 3     /**
 4      * @param str: a string
 5      * @param offset: an integer
 6      * @return: nothing
 7      */
 8     void rotateString(string &str, int offset) {
 9         // wirte your code here
10         // empty string->return
11         if ("" == str) {
12             return;
13         }
14         // offset is 0, return
15         int size = str.size();
16         offset = offset%size;
17         if (0 == offset) {
18             return;
19         }
20         // tmp = str+str->substr
21         string tmp(str);
22         tmp.reserve(size<<1);
23         tmp.insert(tmp.end(), str.begin(), str.end());
24         str = tmp.substr(size-offset, size);
25     }
26 };

 C++,

time:O(n)

space:O(1)

 1 class Solution {
 2 public:
 3     /**
 4      * @param str: a string
 5      * @param offset: an integer
 6      * @return: nothing
 7      */
 8     void rotateString(string &str, int offset) {
 9         // wirte your code here
10         // empty string->return
11         if ("" == str) {
12             return;
13         }
14         // offset is 0, return
15         int size = str.size();
16         offset = offset%size;
17         if (0 == offset) {
18             return;
19         }
20         // 3-steps reverse
21         reverse(str, 0, size-offset-1);
22         reverse(str, size-offset, size-1);
23         reverse(str, 0, size-1);
24     }
25     void reverse(string &str, int from, int to) {
26         char tmp;
27         while( from<to ) {
28             tmp = str[from];
29             str[from] = str[to];
30             str[to] = tmp;
31             from++;
32             to--;
33         }
34     } 
35 };

 

LintCode: Rotate String

原文:http://www.cnblogs.com/CheeseZH/p/4999687.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!