[LeetCode] Reverse Words in a String

AC360变频器使用案例 AC360变频器使用案例! 阅读详情

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.

java实现
public String reverseWords(String s) {
        String newString = s.trim();
		if(newString.length()<=0) return s.trim();
		String []splitsStrings = newString.split(" ");
		int len = splitsStrings.length;
		StringBuilder sBuilder = new StringBuilder("");
		for(int i=len-1;i>=0;i--){
			if(splitsStrings[i].length()>0){
				sBuilder.append(splitsStrings[i]);
				sBuilder.append(" ");
			}
		}
		String resultString = sBuilder.toString();
		return resultString.trim();
    }
  • public String trim()
    Returns a copy of the string, with leading and trailing whitespace omitted.

    If this String object represents an empty character sequence, or the first and last characters of character sequence represented by thisString object both have codes greater than '\u0020' (the space character), then a reference to thisString object is returned.

    Otherwise, if there is no character with a code greater than '\u0020' in the string, then a newString object representing an empty string is created and returned.

    Otherwise, let k be the index of the first character in the string whose code is greater than'\u0020', and let m be the index of the last character in the string whose code is greater than'\u0020'. A new String object is created, representing the substring of this string that begins with the character at indexk and ends with the character at index m-that is, the result ofthis.substring(k, m+1).

    This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

    Returns:
    A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
  • StringBuilder
    public StringBuilder(String str)
    Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument.
    Parameters:
    str - the initial contents of the buffer.
    Throws:
    NullPointerException - if str is null

C++

Analysis:

The clarification is  very important, during the interview, one should think of these points without hint, and then implement the algorithm.

By checking the clarifications, the programming is straightforward, here provides a simple version which uses buffer strings:
(1) Loop from start to the end of the string:
          (a) if current char is space and word string is empty, continue.
          (b) if current char is space but word string is NOT empty, which means we meet the end of word, then output the word, reset the word, continue.
          (c) if current char is non-space char, add this char to the word string, continue
(2) Handle the last word:
      (a) if the last word is empty, which means the input is empty, or the input has only spaces, or the last char/chars are spaces.  Then just remove the last space in the output string and return.
      (b) if the last word is not empty, add the last word to the front of the output string, then remove the last space in the output string and return.

void reverseWords(string &s) {
    string word;//tmp string to store each word
    string res;// result string
    int i = 0;
    for(int i=0;i<s.size();i++){
        if(s[i]==' ' && word.empty()) continue;//multiple spaces
        if(s[i]==' ' && !word.empty()){// word ends
            res = word+" "+res;// add word to result string
            word = "";// reset the word
            continue;
        }
        if(s[i]!=' '){//non space characters
            word.push_back(s[i]);
            continue;
        }
    }
    if(!word.empty())//last word
        s = word+" "+res;
    else
        s = res;
    s = s.substr(0,s.size()-1);
}



AI测试实战:手把手教你做LLM(大模型)性能测试「含完整代码」 大模型API性能测试是评估模型服务响应能力、吞吐量和资源效率的关键手段。核心指标包括总响应时间、吐字率、首token延迟、输入/输出tokens数量、QPM等。测试流程涵盖构造负载、并发请求、数据采集和指标计算。优化建议针对吐字率低、首token延迟高、QPM偏低等问题,从模型、硬件、系统等多层面提出解决方案。 阅读详情

相关推荐

告别降级CUDA!手把手教你为RTX 50系显卡(5080/5090)配置专属的PyTorch Nightly + vLLM推理环境

本文详细指导如何为RTX 50系显卡(5080/5090)配置专属的PyTorch Nightly和vLLM推理环境,特别针对CUDA 12.8的适配问题提供解决方案。从硬件准备到源码编译,再到模型部署与性能调优,手把手教你构建高效AI推理系统。

weixin_33724046的博客 413

Reverse Words in a String

题目:Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". 思路:用栈实现,利用两个栈stackWord,stackSentence,一个存单词,一个存句子,遇到“ ”之前将字符存于stack

oGerald1的博客 329

谐振电路原理与应用场景全解析

本文全面解析了谐振电路的原理、类型及其核心应用。详细阐述了串联谐振与并联谐振的工作特性,并重点介绍了其在无线通信调谐、音频处理分频以及电力系统滤波与无功补偿等关键场景中的实际作用。通过公式推导与实例分析,帮助读者深入理解LC谐振的选频与能量交换机制。

t1u2v的博客 847

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

desmondbcfntu的专栏 647

鼎捷T100—二次开发:客制化联络对象维护作业 aooi350

鼎捷T100二次开发,客制化

weixin_52342654的博客 1137

致远OA系统表单相关操作记录(一)

致远OA系统表单相关操作

weixin_59666050的博客 6155

LeetCode实战:翻转字符串里的单词

题目英文 Given an input string, reverse the string word by word. Example 1: Input: "the sky is blue" Output: "blue is sky the" Example 2: Input: " hello world! " Output: "world! hello" Explanation: Your ...

老马的程序人生 914

1、世界级模拟电路设计指南

本文详细探讨了模拟电路设计的各个方面,从基础概念到实际应用,涵盖了元件选择、滤波器设计、反馈系统、噪声问题以及SPICE仿真的优缺点。文中还提供了设计实例和无计算机设计方法,旨在帮助工程师提升模拟电路设计的效率与可靠性。

s1t2u3的博客 102

LeetCode2—String字符串中单词翻转

Reverse Words in a String Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Clarification: What constitutes

xietingcandice的专栏 661

4、基于球面波展开的近场/远场变换技术解析

本文深入解析了基于球面波展开的近场/远场变换技术,涵盖坐标系统选择、截断测量处理、高级SWE方法及实际应用场景。重点介绍了广义SWE、全探头补偿、平移SNF测量(TSWE)等关键技术,结合吸收材料与导电地板系统的误差处理方案,系统总结了各类方法的优缺点与适用场景,并通过流程图和案例分析展示了技术应用路径。该技术在汽车、通信和航空航天领域的天线测量中具有重要价值,可显著提升测量效率与精度。

dell8的博客 266

Python之afdx包语法、参数和实际应用案例

Python 的 afdx 包是针对 AFDX 协议的轻量级开发工具,专注于 AFDX 数据帧的解析、构造、发送/接收、协议合规性校验等核心能力,广泛应用于航空电子设备测试、仿真、数据监控等场景。

王国平的博客 990

Reverse Words in a String (LeetCode)

题目: Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Clarification: What constitutes a word? A sequence of

yun1221的专栏 | Smile, open your eyes, love and go on 1036

UNet + Shuffle Attention:一种轻量高效的医学图像分割注意力机制

本文提出了一种轻量高效的医学图像分割方法,将Shuffle Attention模块嵌入UNet的上采样路径中。Shuffle Attention通过通道分组注意力机制增强关键特征,同时保持计算轻量化。该方法在上采样后应用注意力模块,有效融合高层语义与低层细节,计算开销小且易于部署。实验表明,该模型在保持UNet原有优势的基础上,通过注意力机制提升了特征聚焦能力,适用于多种图像分割任务。未来可进一步结合空间注意力或Transformer模块以增强模型性能。

Henry的博客 245

LeetCode 557. Reverse Words in a String III (Java版; Easy)

welcome to my blog LeetCode Top Interview Questions 557. Reverse Words in a String III (Java版; Easy) 题目描述 Given a string, you need to reverse the order of characters in each word within a sentence whi...

littlehaes的博客 299

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

刷leetcode的第一道题——Reverse Words in a String

好久没在Online Judge上做题了,今天

fmt.Println( 2704

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

LeetCode - Reverse Words in a String I && II

https://leetcode.com/problems/reverse-words-in-a-string/ 这道题O(n)的方法很简单,就是遍历字符串,找到一个词就放到list里面,遍历完后把list里面的单词从后往前连起来就行。 而且本来我想用JAVA的s.split(" ")函数的,结果leetcode的用例全部都是不规律的,两个单词间N多空格,或者字符串前后都是空格之类的,所以用s

chilakaka的专栏 419

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

【LeetCode】557.Reverse Words in a String III

题目:https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ 我的代码+学习代码

Fannie08的博客 324

[Leetcode] 151. Reverse Words in a String

link: https://leetcode.com/problems/reverse-words-in-a-string/ Solution: split + reverse class Solution { public String reverseWords(String s) { if(s.length() == 0) return s; Strin...

Renoler的博客 142

Leetcode 557 Reverse Words in a String Ⅲ

Leetcode 557 Reverse Words in a 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. Examp...

qq_43271202的博客 200

[Leetcode] 557. Reverse Words in a String III

link: https://leetcode.com/problems/reverse-words-in-a-string-iii/ Solution: spilt + reverse class Solution { public String reverseWords(String s) { if(s.length() == 0) return s; S...

Renoler的博客 149

Leetcode 151 Reverse Words in a String

lc151 Reverse Words in a String 利用split(),将String分成一个String[],可以用正则表达式"\\s+"(第一个\转义,\s表示空格,+表示多个空格),也可以直接用" ",第二种方法快一些 然后按题意翻转即可,从后面遍历String,一次将元素放入新String(这里可以用StringBuilder,会比直接用+连接字符串快,最后sb.toStr...

weixin_30609331的博客 103

【leetcode】557. Reverse Words in a String III

Algorithm 【leetcode】557. Reverse Words in a String III https://leetcode.com/problems/reverse-words-in-a-string-iii/ 1)problem Given a string, you need to reverse the order of characters in each w...

weixin_30319097的博客 117

【Leetcode】557. Reverse Words in a String III

题目地址: https://leetcode.com/problems/reverse-words-in-a-string-iii/ 给定一个英文句子,单词以空格分隔。要求将句子中所有单词翻转,返回翻转后的句子。代码如下: public class Solution { public String reverseWords(String s) { if (s == null...

数学、算法爱好者的博客 226

【leetcode】【medium】【每日一题】151. Reverse Words in a String​​​​​​​

151. Reverse Words in a String Given an input string, reverse the string word by word. Example 1: Input: "the sky is blue" Output:"blue is sky the" Example 2: Input: " hello world! " Output...

lemonade13的博客 147

Task4:LeetCode1:twoSum; LeetCode344:Reverse String;LeetCode151:Reverse Words in a String

1.Two Sum(两个数求和) class Solution: def twoSum(self, nums: 'List[int]', target: int) -> 'List[int]': dicti = {} for i, n in enumerate(nums): if n in dicti: ...

m0_37548423的博客 169

LeetCode | Reverse Words in a String

题目: Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". 思路: 方法1:首先把句子看做由词组成的,例如“A B C”,因此可以将句子的所有字符前后交换,得到“C

Allan的专栏 2万+
上一篇: [LeetCode43] Multiply Strings
下一篇: [LeetCode] Path Sum
Mavs
博客等级 码龄17年 166粉丝 296原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值