【LeetCode with Python】 Reverse Words in a String
2008-12-07 13:04
756 查看
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/reverse-words-in-a-string/
题目类型:字符串,两指针问题
难度评价:★
本文地址:/article/1377552.html
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
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.
反转一句话中的单词。注意题中还要求去除首尾可能存在的空白字符,词与词之间也要去除多余空白字符,而只留一个空白。
原题页面:https://oj.leetcode.com/problems/reverse-words-in-a-string/
题目类型:字符串,两指针问题
难度评价:★
本文地址:/article/1377552.html
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.
反转一句话中的单词。注意题中还要求去除首尾可能存在的空白字符,词与词之间也要去除多余空白字符,而只留一个空白。
class Solution: # @param s, a string # @return a string def reverseWords(self, s): len_s = len(s) if len_s < 1: return s index_right = len_s - 1 new_s = "" while index_right >= 0: while index_right >= 0 and ' ' == s[index_right]: index_right -= 1 end_index = index_right while index_right >= 0 and ' ' != s[index_right]: index_right -= 1 start_index = index_right + 1 word = s[start_index : end_index + 1] if end_index >= 0 else "" new_s += (word + " ") return new_s.rstrip()
相关文章推荐
- [LeetCode]题解(python):151-Reverse Words in a String
- [leetcode, python] Reverse Words in a String 反转字符串
- python:leetcode之reverse words in a string
- leetcode 【 Reverse Words in a String 】python 实现
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode]Reverse Words in a String(using Python)
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- leetcode:Reverse Words in a String【Python版】
- 【leetcode】Reverse Words in a String (python)
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode]Reverse Words in a String @ Python
- Leetcode - Python - Reverse Words in a String
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- 151. Reverse Words in a String Leetcode Python