首页 > 其他分享 >leetcode 557. Reverse Words in a String III

leetcode 557. Reverse Words in a String III

时间:2023-05-30 18:04:32浏览次数:47  
标签:word String int 557 split Words ans reverseWords string

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

 

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        # split world, for echo one reverse it and join it.
        """
        ans = ""
        flag = True
        for word in s.split(" "):
            if flag:                
                ans += word[::-1]
                flag = False
            else:
                ans += " "+word[::-1]
        return ans
        """
        #return " ".join(w[::-1] for w in s.split(" "))
        ans = ""
        for word in s.split(" "):
            ans += word[::-1] + " "
        return ans.strip()

个人倾向于一行代码搞定。

解法2: 耗时较" ".join(w[::-1] for w in s.split(" "))

# Here I first reverse the order of the words and then reverse the entire string.

def reverseWords(self, s):
    return ' '.join(s.split()[::-1])[::-1]

 写一个c++的,贪心:

class Solution {
public:
    void reverseWord(string &s, int i, int j) {
        char c;
        while(i < j) {
            c = s[j];
            s[j--] = s[i];
            s[i++] = c;
        }
    }
    
    string reverseWords(string s) {
        int len= s.length();
        for(int i=0; i<len; ) {
            int j = i;
            while (j<len && s[j] != ' ') j+=1;
            reverseWord(s, i, j-1);
            i = j+1;
        }
        return s;
    }
};

 

class Solution {
public:
    string reverseWords(string s) {
        size_t front = 0;
        for(int i = 0; i <= s.length(); ++i){
            if(i == s.length() || s[i] == ' '){
                reverse(&s[front], &s[i]);
                front = i + 1;
            }
        }
        
        return s;
    }
};

 

标签:word,String,int,557,split,Words,ans,reverseWords,string
From: https://blog.51cto.com/u_11908275/6381148

相关文章

  • leetcode 541. Reverse String II
    Givenastringandanintegerk,youneedtoreversethefirstkcharactersforevery2kcharacterscountingfromthestartofthestring.Iftherearelessthankcharactersleft,reverseallofthem.Iftherearelessthan2kbutgreaterthanorequalt......
  • leetcode 345. Reverse Vowels of a String
    Writeafunctionthattakesastringasinputandreverseonlythevowelsofastring.Example1:Givens="hello",return"holle".Example2:Givens="leetcode",return"leotcede".Note:Thevowelsdoesnotincl......
  • 3.1. 字符串与StringBuilder
    1.字符串(String)在Java中,字符串由String类表示。字符串是一系列字符的组合,用于表示文本数据。字符串是不可变的,这意味着一旦创建了一个字符串对象,就不能修改它的内容。创建字符串创建字符串的方式有两种:直接使用双引号("")创建字符串字面量。例如:Stringstr1="Hello,World!......
  • 分组,捕获,反向引用以及String类中使用
    1. 提出要求  896请看下面问题:给你一段文本请你找出所有四个数字连在一 起的子串,并且这四个数字要满足①第1位与第4位相同②第2位与第3位相同,比如1221,5775,……2. 介绍  896要解决前面的问题,我们需要了解正则表达式的几个概念:1. 分组我们可以用圆括号组成一个比较复杂的匹......
  • CodeForces 1830C Hyperregular Bracket Strings
    洛谷传送门CF传送门每一步思路都非常自然的题。考虑先从一些简单的case入手。1.\(k=0\)设\(g_i\)为长度为\(i\)的合法括号串数。显然\(\foralli\nmid2,g_i=0\)。对于偶数的\(i\),这是一个经典问题,\(g_i\)就是第\(\frac{i}{2}\)项卡特兰数,因此\(g_i=\bi......
  • JSON.parse 和 JSON.stringify()
    这篇文章主要介绍了JSON.parse()和JSON.stringify()使用。parse用于从一个字符串中解析出json对象,如varstr='{"name":"huangxiaojian","age":"23"}'结果:JSON.parse(str)Objectage:"23"name:"huangxiaojian"__proto__:Object注......
  • String验证码案例
    packagecom.String;importjava.util.Random;publicclassSrtingDemo2{//验证码publicstaticvoidmain(String[]args){System.out.println(createCode(4));System.out.println(createCode(6));}//设计一个方法,返回指定位数的......
  • String使用时的几个注意事项
    packagecom.String;publicclassSrtingDemo1{publicstaticvoidmain(String[]args){//String使用时的几个注意事项//1.String的对象是不可变的Stringname="黑马";name+="程序员";name+="波妞";......
  • 快速熟悉String提供的处理字符串的常用方法
    packagecom.String;publicclassStringDemo{publicstaticvoidmain(String[]args){//快速熟悉String提供的处理字符串的常用方法Strings="黑马java";//1.获取字符串长度System.out.println(s.length());//2.提取字......
  • String案例
    packagecom.String;importjava.util.Scanner;publicclassuserDemo{publicstaticvoidmain(String[]args){for(inti=0;i<3;i++){Scannersc=newScanner(System.in);System.out.println("请您输入登录名称:");......