面试问题:从字符串修剪多个连续的空格 [英] Interview Question : Trim multiple consecutive spaces from a string

查看:92
本文介绍了面试问题:从字符串修剪多个连续的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题
寻找最佳的最佳解决方案修剪字符串中的多个空格。这个操作应该是就地操作。

This is an interview question Looking for best optimal solution to trim multiple spaces from a string. This operation should be in-place operation.

input  = "I    Like    StackOverflow a      lot"
output = "I Like StackOverflow a lot"

字符串函数是不允许的,因为这是一个面试问题。寻找问题的算法溶液

String functions are not allowed, as this is an interview question. Looking for an algorithmic solution of the problem.

推荐答案

请两个指标:下一个可用的位置把一封信中(例如, I ),并你检查当前的指数(例如,Ĵ)。

Keep two indices: The next available spot to put a letter in (say, i), and the current index you're examining (say, j).

有超过所有字符只是循环Ĵ,每当你看到一个字母,将其复制到指数 I ,然后增加 I 。如果你看到这不是一个空格pceded $ P $的空间,也复制的空间。

Just loop over all the characters with j, and whenever you see a letter, copy it to index i, then increment i. If you see a space that was not preceded by a space, also copy the space.

我的认为的这会工作在地方...

I think this would work in-place...

这篇关于面试问题:从字符串修剪多个连续的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆