剑指offer 58 翻转字符串

题目一:

输入一个英文句子,翻转句子中单词的顺序,但单词内字符的句子顺序不变。标点符号和普通字母一样处理

例如输入字符串“I am a student.”输出“student.  a am I”

思路:

1翻转句子中所有的字符——>.tueduts a ma I

2翻转每个单词中的字符顺序

代码:

 class Solution{
public:
  void Reverse (string &str,int begin,int end)
{
  if(begin<0||end<0)
    return;
  while(begin<end)
 {
   char temp=str[begin];
   str[begin]=str[end];
   str[end]=temp;

   begin++;
   end--;
  }
}

string 	ReverseSentence(string str)
{
  int n=str.size();
  if(n==0)
  return str;
  int begin=0;
  int end=n-1;
  //翻转整个句子
  Reverse(str,begin,end);
  //翻转每个单词
  begin=end=0;
  while(str[begin]!='\0')
  { 
   if(str[begin]==' ')//防止出现连续空格的字符
    {
     begin++;
     end++;
    }
   else if(str[end]==' '||str[end]='\0')
   {
   Reverse(str,begin,--end);
   begin=++end;
   }
   else end++;
  }
 }
};
  
题目二:

左旋转字符串

对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。

思路:

  • 和上面的思路类似,我们可以将字符串分成两部分,先分别翻转两部分子字符串;
  • 然后对翻转后的字符串整体再进行一次翻转。
  • 代码:
class Solution {
public:
    string LeftRotateString(string str, int n) {
        int length=str.size();
        
       if(length>0&&n>0&&n<length)
       { int begin1=0;
        int end1=n-1;
        int begin2=n;
        int end2=length-1;
        Reverse(str,begin1,end1);
        Reverse(str,begin2,end2);
        Reverse(str,0,length-1);
    }   
   return str;
} void Reverse(string &str,int begin,int end) { if(begin<0||end<0) return; while(begin<end) { char temp=str[begin]; str[begin]=str[end]; str[end]=temp; begin++;end--; } }};




猜你喜欢

转载自blog.csdn.net/weixin_41413441/article/details/80680710