个性化阅读
专注于IT技术分析

Python代码以单次遍历将空格移到字符串的开头

点击下载

给定一个包含单词和空格的字符串, 编写一个程序, 通过仅遍历字符串一次, 将所有空格移到字符串的开头。

例子:

Input  : str = "geeks for geeks"
Output : ste = "  srcmini"

Input  : str = "move these spaces to beginning"
Output : str = "    movethesespacestobeginning"
There were four space characters in input, all of them should be shifted in front.

此问题已有解决方案,请参考单遍历链接将空格移到字符串前面。

我们将在Python中使用列表理解快速解决这个问题。

方法:

  1. 使用列表推导遍历输入字符串并创建一个没有任何空格字符的字符串。
  2. 现在要知道原始字符串中有多少个空格字符, 只需将原始字符串和新字符串的长度相差即可。
  3. 现在创建另一个字符串, 并在开头添加空格字符。
# Function to move spaces to front of string
# in single traversal in Python
  
def moveSpaces( input ):
      
     # Traverse string to create string without spaces
     noSpaces = [ch for ch in input if ch! = ' ' ]
  
     # calculate number of spaces
     space = len ( input ) - len (noSpaces)
  
     # create result string with spaces
     result = ' ' * space
  
     # concatenate spaces with string having no spaces
     result = '"'+result + ''.join(noSpaces)+'"'
     print result
  
# Driver program
if __name__ = = "__main__" :
     input = 'geeks for geeks'
     moveSpaces( input )

输出如下:

"  srcmini"

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python代码以单次遍历将空格移到字符串的开头

评论 抢沙发

评论前必须登录!