zoukankan      html  css  js  c++  java
  • 关于“就地颠倒句子里的词”面试题

    暂时无法访问博客堂,先贴到这里了,等能访问了再复制过去……
    其实这问题源于轻剑傲风解答尉迟方兄遇到的面试题那个帖子。这道题如下:

    1、reverse a sentence in place.
    例子:I am yuchifang -> yuchifang am I
    注意in place

    关键点在于“in place”,即“就地”。我的理解是,要求这个转换所占的全部空间限于原字符串所在的地址空间,不得使用额外的存储空间。轻剑傲风已经给出了一种解答方案,思路的确是满足了in place的要求,但是缺点是解答过程中用了VB的字符串函数StrReserve和Replace。我觉得这就不太对了,因为你无法保证StrReserve或者Replace函数执行的过程没有采用额外的存储空间。事实上,.NET字符串一旦创建,就不能改动,所以所有字符串函数肯定都是“非就地”的。所以在.NET语言中解这道题,我们就不能直接对String进行操作,或用任何现有的字符串函数,而是要在Char数组上进行操作。
    下面是我用轻剑傲风的思路重新写了一遍,但没有用任何字符串函数,整个过程完全“就地”解决,没有将一个字符写到原数组的存储空间之外。代码中有将System.String转换成Char[]的代码,这个不应该算我算法中的一部分。此外我还用了String.Length,不得不用一下,虽然解法最好不包含任何.NET的内置函数……
    语言是:C++/CLI
    // ReverseInPlace.cpp: 主项目文件。

    #include 
    "stdafx.h"

    using namespace System;

    template 
    <typename T>
    void SwapInPlace(interior_ptr<T> a, interior_ptr<T> b)
    {
        
    *= *^ *b;
        
    *= *^ *b;
        
    *= *^ *b;
    }


    int main(array<System::String ^> ^args)
    {
        
    if (args->Length > 0)
        
    {
            String
    ^ s = args[0];
            
            
    int length = s->Length; //risk: CLR property
            
            
    if (length < 1)
            
    {
                
    return 0;
            }


            
    //Step one, reverse the string in place.
            array<Char>^ chararr = s->ToCharArray();
            
    for (int i = 0; i < (length - 1/ 2.0; i++)
            
    {
                SwapInPlace
    <Char>(&chararr[i], &chararr[length - 1 - i]);
            }


            
    //Step two, reverse every word in place.
            int lastSpace = 0;
            
    for (int j = 0; j <= length; j++)
            
    {
                
    if (j == length || chararr[j] == ' ')
                
    {
                    
    for (int k = lastSpace; k < lastSpace + (j - 1 - lastSpace ) / 2.0; k++)
                    
    {
                        SwapInPlace
    <Char>(&chararr[k], &chararr[j - 1 - k + lastSpace]);
                    }

                    lastSpace 
    = j + 1;
                }

            }


            Console::WriteLine(chararr);
        }

        
        
    return 0;
    }
      小测试了一把,但是说不定还有Bug。其实这道题考的就是看你够不够仔细,会不会有Bug,呵呵。
  • 相关阅读:
    centos6.9安装xampp后报错:egrep: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory
    linux如何安装xampp,以及融合dvwa
    CSS的伪元素和伪类
    Font Awesome:图标字体,完全CSS控制
    SoapUI接口测试·第一个HTTP Request接口请求和断言
    Http 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete .
    Web接口测试工具---Poster与Postman
    WebApi接口传参不再困惑(4):传参详解 一、get请求 二、post请求 三、put请求 四、delete请求 五、总结
    tomcat 禁用不安全的http请求模式 .
    JBOSS的安全配置 .
  • 原文地址:https://www.cnblogs.com/Ninputer/p/139896.html
Copyright © 2011-2022 走看看