對於ios7掃描二維碼功能的實現

來源:互聯網
上載者:User

標籤:string   字串反轉   

題目如下:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
題目要求不僅需要把字串中的單詞進行旋轉,而且測試案例中還包含頭尾含有空格、單詞間空格數大於1個之類的字串。所以要處理好空格,處理完空格的字串肯定是小於或等於原字串長度的,考慮到通過移動字元的方式來減小空格耗時間長度,我的思路是首先計算出去多餘的空格後字串應有的長度,然後重新定義一個臨時字串,開闢最終應有長度的空間。然後將原字串逆序copy到新定義的字串變數中,保證頭尾多餘空格已去除,保證單詞間僅保留一個空格。然後將每個單詞再進行一次反轉,便實現了題目所要求的功能。AC代碼如下:
class Solution {public:    void reverseWords(string &s) {if(s.empty())return;int count = 0;int index = 0, indexTemp = 0, begin = 0, end = s.length()-1;while(s[begin] == ' ' && begin<s.length()-1)begin++;while(s[end] == ' ' && end>0)end--;if(end == 0 && s[end] == ' '){s = "";return;}else if(end == 0){s = s.substr(0,1);return;}index = begin;while(index <= end){if(s[index] == ' '){count++;while(s[index] == ' ')index++;}count++;index++;}string temp(count,'\0');index = end;indexTemp = 0;while(index >= begin){if(s[index] == ' '){temp[indexTemp] = s[index];while(s[index] == ' ')index--;indexTemp++;}temp[indexTemp] = s[index];indexTemp++;index--;}indexTemp = 0;begin = -1;end = -1;while(indexTemp < count){if(temp[indexTemp] != ' ' && begin == -1){begin = 0;}else if(indexTemp-1 >= 0 && temp[indexTemp-1] == ' '&&temp[indexTemp] != ' '){begin = indexTemp;}else if((indexTemp+1 < count && temp[indexTemp+1] == ' ' && temp[indexTemp] != ' ') || ((indexTemp == count-1)&&temp[indexTemp] != ' ')){end = indexTemp;reverse(temp, begin, end);}indexTemp++;}s = temp;    }void reverse(string &s, int begin, int end){while(begin < end){char temp = s[begin];s[begin] = s[end];s[end] = temp;begin++;end--;}}};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.