zoukankan      html  css  js  c++  java
  • #Leetcode# 151. Reverse Words in a String

    https://leetcode.com/problems/reverse-words-in-a-string/

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

    Example:  

    Input: "the sky is blue",
    Output: "blue is sky the".
    

    Note:

    • A word is defined as a sequence of non-space characters.
    • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
    • You need to reduce multiple spaces between two words to a single space in the reversed string.

    代码:

    class Solution {
    public:
        void reverseWords(string &s) {
            int len = s.length();
            int newlen = 0;
            reverse(s.begin(), s.end());
            for(int i = 0; i < len; i ++) {
                if(s[i] != ' ') {
                    if(newlen != 0) s[newlen ++] = ' ';
                    int temp = i;
                    while(temp < len && s[temp] != ' ')
                        s[newlen ++] = s[temp ++];
                    
                    reverse(s.begin() + newlen - (temp - i), s.begin() + newlen);
                    
                    i = temp;
                }
            }
            s.resize(newlen);
        }
    };
    

    $char$ 代码:

    #include <bits/stdc++.h>
    using namespace std;
    
    char s[1010];
    char ans[1010][30];
    
    int main() {
        cin.getline(s, 1010);
        int len = strlen(s);
        s[len] = ' ';
        len ++;
        s[len] = '';
    
        int cnt = 0;
        for(int i = 0; i < len; i ++) {
            if(s[i] != ' ')
            for(int j = i; j < len; j ++) {
                if(s[j] != ' ') continue;
                else {
                    cnt ++;
                    for(int k = i; k < j; k ++)
                        ans[cnt][k - i] = s[k];
    
                    i = j;
                    break;
                }
            }
        }
    
        for(int i = 1; i <= cnt; i ++)
            cout << ans[i] << endl;
        return 0;
    }
    View Code

      很神奇诶 以前只写过 $char$ 的反转 讲真 $string$ 是真的不怎么会 这道题是先整个反转 然后找到每个单词再反转 $newlen$ 记录新的长度 然后最后重新给 $s$ 分配一个大小为 $newlen$ 的空间 今天依旧是有点菜的一天哦

  • 相关阅读:
    HTML初识
    使用python操作Memcache、Redis、RabbitMQ、
    使用salt-cloud创建虚拟机
    运维堡垒机----Gateone
    ELK日志分析系统
    Python MySQL API
    浅谈Java中static作用--转
    oracle如何设置最大连接数
    转--oracle查看允许的最大连接数和当前连接数等信息
    oracle 查看未关闭连接
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10033502.html
Copyright © 2011-2022 走看看