多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
早上看到好友未央的一篇博文[《一道google的测试工程师笔试题》](http://www.itsbug.com/?p=208),内容如下: ~~~ 这是去年面试google测试工程师的一道题,题目如下: 设计一个函数,使用任意语言,完成以下功能: 一个句子,将句子中的单词全部倒排过来,但单词的字母顺序不变。比如,This is a real world,输出结果为world real a is this. ~~~ 他用C++很好的封装了一个函数实现了此功能,如下,更多信息请访问:[http://www.itsbug.com/?p=208](http://www.itsbug.com/?p=208) C++版本: ~~~ #include <iostream> #include <string.h> using namespace std; const char *Reverse(char *src); char *pDst=NULL; int main(int argc,char **argv) { cout << "please input your sentense:" << endl; char pSrc[100]; memset(pSrc,0,100); cin.getline(pSrc,100); cout << Reverse(pSrc) << endl; if (pDst != NULL)delete pDst; return 0; } const char *Reverse(char *pSrc) { char *pPos = pSrc; int iLen=strlen(pSrc); pDst = new char[iLen + 1]; memset(pDst,0,iLen+1); int iCurrentPos = 0; int iPrePos = 0; while (pPos) { if (pSrc[iCurrentPos] <= 'z' && pSrc[iCurrentPos] >= 'A') { iCurrentPos++; pPos ++; continue; } else { int iDistance =iCurrentPos-iPrePos; for (int i=0;i < iDistance;i++) { pDst[iLen - iCurrentPos+i] = pSrc[iPrePos+i]; } pDst[iLen-iCurrentPos-1]=pSrc[iCurrentPos]; iCurrentPos ++; } iPrePos = iCurrentPos; if (*pPos == '\0') { break; } else { pPos ++; } } return pDst; }    memset(pDst,0,iLen+1);    int iCurrentPos = 0;    int iPrePos = 0;    while (pPos)    {        if (pSrc[iCurrentPos] <= 'z' && pSrc[iCurrentPos] >= 'A')        {            iCurrentPos++;            pPos ++;            continue;        }        else        {            int iDistance =iCurrentPos-iPrePos;            for (int i=0;i < iDistance;i++)            {            pDst[iLen - iCurrentPos+i] = pSrc[iPrePos+i];            }            pDst[iLen-iCurrentPos-1]=pSrc[iCurrentPos];            iCurrentPos ++;        }        iPrePos = iCurrentPos;        if (*pPos == '\0')        {            break;        }        else        {            pPos ++;        }    }    return pDst; } ~~~ 想了一下,如果此功能使用python来实现的话,可能比较方便,大致思路如下: 1. 将语句中的单词提取出来放入list中; 2. 将list反转; 3. 将反转后的list输出。 实现如下: python版本: ~~~ #!/usr/bin/env python # -*- coding: utf-8 -*- def str_reverse(str_src): ''' Function:返转单词,以空格或TAB键为间隔符 Input:NONE Output: NONE author: socrates blog:http://blog.csdn.net/dyx1024 date:2012-02-18 ''' #以空格为分隔符,将各单词取出来存放在list中 str_dst = str_src.split() #反转list str_dst.reverse() #返回反转后的list对象 return str_dst if __name__ == '__main__': #遍历list,输出内容 for str_out in str_reverse(raw_input("please input your sentense:")): print str_out, ~~~ 测试: ~~~ [root@kevin python_test]# ./str_test.py please input your sentense:This is a real world world real a is This [root@kevin python_test]# ./str_test.py please input your sentense:中国 陕西 西安 西安 陕西 中国 [root@kevin python_test]# ~~~