You could按照你的方式做两个循环。完成第一个循环后,您必须再次执行该循环,但长度减少一个,以便当前的第一个(最初是第二个)字符被放置在最后第二位置,保留当前最后一个(最初是第一个)字符。然后继续下去,直到长度降至零。
But that's pretty inefficient since you have the nested loops, O(n2). Here's a better algorithm that uses just one loop, O(n):
set spointer to point to the first character
set epointer to point to the last character
while epointer is greater than spointer:
save away [spointer] (the character pointed to by spointer) somewhere
copy [epointer] to [spointer]
copy the saved character to [epointer]
add one to spointer
subtract one from epointer
它基本上维护一个开始和结束指针,最初交换第一个和最后一个字符,然后指针向彼此移动。
因此,第二次循环时,交换第二个和倒数第二个字符,第三次交换第三个和倒数第三个字符,依此类推。
当指针相等(对于奇数长度字符串)或起始指针大于结束指针(对于偶数长度字符串)时,此过程停止。
由于这可能是家庭作业(无论如何,您似乎都在加快 x86 的速度),因此您应该执行将其转换为汇编程序的练习。
如果结果是not作为家庭作业,您可以使用下面的 masm32 代码作为基准。请不要试图将其冒充为您自己的教育工作,因为您几乎肯定会被抓住。你会学到更多东西(作为家庭作业or非家庭作业)如果您自己解决转换问题,我只是提供一些后备代码(如果您在解决问题时遇到困难)。
.586
.model flat
.data
source byte "This is the source string", 0
.code
_main proc
mov esi, offset source ; load up start pointer.
mov edi, offset source ; set end pointer by finding zero byte.
dec edi
find_end:
inc edi ; advance end pointer.
mov al, [edi] ; look for end of string.
cmp al, 0
jnz find_end ; no, keep looking.
dec edi ; yes, adjust to last character.
swap_loop:
cmp esi, edi ; if start >= end, then we are finished.
jge finished
mov bl, [esi] ; swap over start and end characters.
mov al, [edi]
mov [esi], al
mov [edi], bl
inc esi ; move pointers toward each other and continue.
dec edi
jmp swap_loop
finished:
int 3 ; trap to enter debugger and check string.
; replace with whatever you need.
_main endp
end _main