zoukankan      html  css  js  c++  java
  • leetcode-Reverse Words in a String

    Reverse Words in a String

     Total Accepted: 15012 Total Submissions: 108513My Submissions

    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.

    Have you been asked this question in an interview? 


    此题要翻转一个字符串中的单词,属于比較简单的字符串处理题。



    C++:
    直接扫描字符串把遇到的单词插入到deque的前面。扫描完把deque容器内的单词拼起来就可以。

    class Solution {
    public:
        void reverseWords(string &s) {
            deque<string> ds;
            int b, i(0), len(s.size());
            while (i < len) {
                while (i<len && s[i]==' ') ++i;
                if (i == len) break;
                b = i;
                while (i<len && s[i]!=' ') ++i;
                ds.push_front(s.substr(b, i-b));
            }
            s = "";
            if (ds.empty()) return;
            s += ds[0];
            for (i=1; i<ds.size(); ++i) s += " " + ds[i];
            
        }
    };
    可是假设加上限制呢?比方不能利用额外线性空间复杂度,又该怎样解呢?临时还没想到。

    Python:
    Python处理更简单了。三行代码就搞定了。

    class Solution:
        # @param s, a string
        # @return a string
        def reverseWords(self, s):
            ss = s.split()
            ss.reverse()
            return " ".join(ss)
            


  • 相关阅读:
    记事本+hhc生成CHM
    在Delphi里实现[int map string]对
    U盘插入拔出提示
    Delphi研发笔试试卷 我的小解
    Excel也能用SQL查询
    访问JAVA中的字段(jfieldID)
    调用JAVA方法
    缓存字段ID和方法ID
    JNI引用
    访问数组(JNI)
  • 原文地址:https://www.cnblogs.com/mthoutai/p/6760771.html
Copyright © 2011-2022 走看看