题解 | #左旋转字符串#
左旋转字符串
http://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec
小白解题
又是这种带顺序的字符数组的变换,老样子,考虑单个又累又不好用,创建新的数组,讲符合要求的放入即可。
需要注意vector与string之间的转换。
代码:
class Solution {
public:
string LeftRotateString(string str, int n) {
int l = str.size();
vector<char>s;
string st;
for(int i=n;i<l;i++){
s.push_back(str[i]);
}
for(int j=0;j<n;j++){
s.push_back(str[j]);
}
return st.assign(s.begin(),s.end());
}
};别人的思路:
看了一下别人的思路,主要有两种:1、讲字符串分为两部分,掉个位置再组合,这里需要用到substr之类的函数;2、挺有意思的解法,字符串分为两部分,每部分翻转一下,然后组合再翻转一下,只是在C++中翻转实现简单吗?
深信服公司福利 838人发布