面試題:反轉字符串

輸入一行字符串,每個單詞之間有至少一個空格,然後反向輸出這些單詞。如輸入 this is a test. 輸出 test a is this。


#include <iostream>

void ReverseStr(std::string& str,int startIndex,int endIndex)
{
    int l = startIndex + (endIndex - startIndex)/2;
    for(int i=startIndex;i<=l;i++)
    {
        std::swap(str[i],str[endIndex+startIndex-i]);
    }
}
int main(int argc, const char * argv[])
{
    
    std::string str = "this is a test";
    int len = 0;
    
    int startIndex = 0;
    int endIndex = 0;
//    printf("ccc:%s",str);
    len = str.length();
    for(int i=0;i<len;i++)
    {
//        printf("ccc:%c",str[i]);
        if(str[i] == ' ' || i==len-1)
        {
            if(i==len-1){
                endIndex = i;
            }else{
                endIndex = i-1;
            }
            printf("startIndex:%d,endIndex:%d\n",startIndex,endIndex);
            ReverseStr(str,startIndex,endIndex);
            startIndex = i+1;
            endIndex = i+1;
        }
    }
    ReverseStr(str,0,len-1);
    printf("result:%s",str.c_str());
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章