43. Title Description
In assembly language, there is a shift instruction called loop left shift (ROL). Now there is a simple task, which is to simulate the operation result of this instruction with a string. For a given character sequence S, please rotate it to the left after K-bit sequence output. For example, the character sequence S = abcXYZdef, which requires the output of the result after the cycle moves 3 bits to the left, i.e. "XYZdefabc". Isn't it simple? OK, get it!
Thinking: XY - > YX
(XT YT) t = = after each substring of YX is inverted, the overall inversion is performed.
class Solution {
public:
string LeftRotateString(string str, int n) {
if(str.empty())
return str;
n=n%str.size();
for(int i=0,j=n-1;i<j;++i,--j)//X->XT
swap(str[i],str[j]);
for(int i=n,j=str.size()-1;i<j;++i,--j)//Y->YT
swap(str[i],str[j]);
for(int i=0,j=str.size()-1;i<j;++i,--j)XTYT->YX
swap(str[i],str[j]);
return str;
}
};
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
if len(s)==0:
return s
n=n%len(s)
return s[n:]+s[:n]
# write code here
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
length=len(s)
if length==0:
return s
n=n%length
s=s[:n][::-1]+s[n:][::-1]
s=s[::-1]
return s
44. Title Description
Niu Ke recently came to a new employee Fish. Every morning, he would always take an English magazine and write some sentences in the book. My colleague cat is very interested in the content written by Fish. One day, he borrowed it from Fish, but he can't understand it. For example, "student. a am I". Later, I realized that this guy turned the order of the words in the sentence. The correct sentence should be "I am a student.". Cat is not good at flipping these words one by one. Can you help him?
class Solution {
public:
void reverse(string &str,int start,int end)
{
for(int i=start,j=end;i<j;++i,--j)
swap(str[i],str[j]);
}
string ReverseSentence(string str) {
if(str.empty())
return str;
reverse(str,0,str.size()-1);
int start=0;
while(start<str.size()) {
while(start<str.size() && str[start]==' ')//Filter space
++start;
int temp=start;
while(start<str.size() && str[start]!=' ')//Get character length
++start;
reverse(str,temp,start-1);
}
return str;
}
};
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
if len(s)==0:
return s
s=s[::-1]
length=len(s)
start=0
while start<length:
while start<length and s[start]==' ':
start+=1
temp=start
while start<length and s[start]!=' ':
start+=1
s=s[:temp]+s[temp:start][::-1]+s[start:]
return s
# write code here