程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode之倒轉一句話單詞

leetcode之倒轉一句話單詞

編輯:C++入門知識

leetcode之倒轉一句話單詞


題目:

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.

    思路:

    這題的思路不用多說,完全是爛大街的題,不就是先以每個單詞為單位,進行翻轉,再以整句話為單位進行翻轉嗎?呵呵,太簡單了,以為簡單你就能做對那可就大錯特錯了,題干裡的的說明還要求去除首尾空格,並壓縮多個空格為一個空格,所以會有N多邊界條件要考慮,我竟然編譯了N次才通過leetcode OJ,作為一個正式工作一年多的程序員,實在是對不起國家,邊界條件的確是考察一個人思維嚴謹性甚至記憶力的試金石!

    代碼:

    class Solution {
    public:
    	Solution(){}
    	void reverse(std::string &s, int f, int e)
    	{
    		while (e>f)
    		{
    			char tmp = s.at(f);
    			s.at(f) = s.at(e);
    			s.at(e) = tmp;
    			f++;
    			e--;
    		}
    	}
    	void squeeze(std::string &s)
    	{
    		int i = 0;
    		std::string re = "";
    		char prev = NULL;
    		bool flag = false;
    		while (i < s.size())
    		{
    			if (s.at(i)!=' ')
    			{
    				if (flag&&prev == ' ')
    				{
    					re.push_back(' ');
    				}
    				re.push_back(s.at(i));
    			}
    			if (s.at(i) == ' '&&prev !=NULL &&prev!= ' ')
    			{
    				flag = true;
    			}
    			prev = s.at(i);
    			i++;
    		}
    		s = re;
    	}
    	void reverseWords(std::string &s) {
    		int i = 0;
    		int f=0, e=0;
    		char prev = ' ';
    		while (i

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved