C/C++字符串转移到特定元素 - 最少可能的步骤
这是我的困境。
例如,我有这个字符串:
"1 2 3 4 5 ..... 100" ,但它可以是任意长度(通常是大得多的长度,谈论的是 4 位数字)。
我需要做的:根据已知位置重新排列字符串的元素。 例如:所讨论的位置是 70。我需要有以下输出: “70 71 ....100 1 2 3 ...69”
条件:
- 我知道关键:例如上面的“70”。也可以是 500、5000,取决于字符串长度。
- 我无法使用任何字符串缓冲区或字符串管理函数。
- 可用内存很少甚至没有。
- 有两个 1 字节缓冲区可用。
- 操作应以尽可能少的步骤完成(时间关键)。
我一直在尝试找到一种不依赖于字符串中键的位置的好的算法。基本上,根据我的一半左右移动,仍然可以进行大量读/写,但我不希望这样。
多谢!
here's my dilema.
I have for example this string:
"1 2 3 4 5 ..... 100" , but it can be any length (usually much, much bigger one, talking about 4 digit numbers).
What I need to do: re-arrange the elements of the string based on a known possition.
E.g: the position in question is 70. I need to have the following output:
"70 71 ....100 1 2 3 ...69"
Conditions:
- I know the key: e.g the above "70". Can be also 500, 5000, depends on the string length.
- I can't use any string buffers or string management functions.
- There's little to none memory available.
- There are two 1 byte buffers available.
- Operation should be done in with the least possible steps (time critical).
I've been trying to find a good algorithm that would not depend on the position of key in the string. Basically shifting left/right depending on what half I am still makes it for a lot of reads/writes and I don't want that.
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这段代码符合你的描述,但你已经很模糊了,我怀疑它能达到你想要的效果...
产生以下输出:
但对于序列一直到
9999
应该同样有效this code fits your decription, but you've been vague enough that I doubt it does what you want...
Produces the following output:
But should work just the same for sequences all the way up to
9999
这就是我在评论中提到的3*reverse方法。只是普通的 C,没有花哨的字符串类。只需要一个存储元素即可进行交换。
对于那些不相信的人,这是结果:
This is the 3*reverse method I mentioned in the comments. Just plain C, no fancy string classes. Needs only one element of storage for the swap.
For those who don't believe, here is the result:
如果您想自己从头开始实现这一点,线索是通过交换字节对,您可以安排将字符串的一部分移动到正确的位置(适当的开头或结尾),从而留下较短的长度仍需要旋转到位的字符串。最终你会用完绳子来旋转。
If you want to implement this yourself from scratch, the clue is that by swapping pairs of bytes you can arrange to move a section of the string into the right place (either the start or the end as appropriate), leaving you a shorter length of string which still needs to be rotated into place. Eventually you will run out of string to rotate.