zoukankan      html  css  js  c++  java
  • 【面试题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         }
  • 相关阅读:
    Java中new关键字和newInstance方法的区别
    一道关于简单界面设计的练习题
    一道关于接口的练习题
    SPSS与聚类分析
    Nunit中文文档
    对比MS Test与NUnit Test框架
    Unit Test单元测试时如何模拟HttpContext
    如何vs升级后10和12都能同时兼容
    LINQ 从 CSV 文件生成 XML
    使用FileSystemWatcher监视文件变化
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4833853.html
Copyright © 2011-2022 走看看