• 【面试题42】翻转单词顺序VS左旋转字符串


    【题目描述】

    输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。

    为简单起见,标点符号和普通字母一样处理。

    例如输入字符串"I am student.",则输出"student. a am I"

    【解决方案】

    先翻转各个单词,再翻转整个句子。

    我的代码实现,仅供参考:

     1         public static void ReverseSentence(char[] chars)
     2         {
     3             if (chars == null || chars.Length < 1)
     4                 return;
     5 
     6             int start = 0;
     7             int end = 0;
     8 
     9             for (int i = 0; i < chars.Length; i++)
    10             {
    11                 if (chars[i] == ' ')
    12                 {
    13                     end = i - 1;
    14                     Reverse(chars, start, end);
    15                     start = i + 1;
    16                 }
    17             }
    18 
    19             Reverse(chars, start, chars.Length - 1);
    20 
    21             Reverse(chars, 0, chars.Length - 1);
    22         }
    23 
    24         public static void Reverse(char[] chars, int start, int end)
    25         {
    26             char temp;
    27             while (start < end)
    28             {
    29                 temp = chars[start];
    30                 chars[start] = chars[end];
    31                 chars[end] = temp;
    32 
    33                 start++;
    34                 end--;
    35             }
    36         }

    【本题扩展】

    字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。

    请定义一个函数实现字符串左旋转操作的功能。

    比如输入字符串"abcdefg"和数字2,该函数将返回左旋转2位得到的结果"cdefgab"。

    方法:分别翻转两部分字符串,然后翻转整个句子。

    我的代码实现,仅供参考:

     1         public static void LeftRotateString(char[] chars, int n)
     2         {
     3             if (chars == null || chars.Length < 1 || n > chars.Length)
     4                 return;
     5 
     6             Reverse(chars, 0, n-1);
     7             Reverse(chars, n, chars.Length - 1);
     8             Reverse(chars, 0, chars.Length - 1);
     9         }
    10 
    11         public static void Reverse(char[] chars, int start, int end)
    12         {
    13             char temp;
    14 
    15             while (start < end)
    16             {
    17                 temp = chars[start];
    18                 chars[start] = chars[end];
    19                 chars[end] = temp;
    20 
    21                 start++;
    22                 end--;
    23             }
    24         }
  • 相关阅读:
    pod 安装
    Mac百度云破解限速-修复选中没有导出下载
    swift -SnapKit一些基本使用
    xcode 显示多个重复模拟器
    xcode选择模拟器显示No Scheme
    Xcode删除指定版本的模拟器
    javaScript基础
    Dao模式多表联查
    SQLServer数据库
    数据库错题分析
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4833853.html
Copyright © 2020-2023  润新知