【发布时间】:2020-02-27 21:11:30
【问题描述】:
我需要帮助来编写一个生成回文的程序。我设法使字符串反转,但我无法将原始字符串和反转字符串组合在一起。当我写 abc 时,我需要得到 abccba,或者当我写 hello 时,我需要得到 helloolleh。现在我只得到 cba 或 olleh。有人可以帮我解决这个问题吗?
.data
msg1: .asciiz "Enter the length of your input: "
msg2: .asciiz "Enter your input: "
msg3: .asciiz "Output of the program is: "
output: .space 256 # will store the output palindrome
.text
la $a0,msg1
li $v0,4
syscall
li $v0,5
syscall
move $s1,$v0 # $s1 has the length of the string
la $a0,msg2
li $v0,4
syscall
li $a1,1024
li $v0,8
syscall
move $s0,$a0 # $s0 has the starting address of the string
#
# YOUR CODE GOES HERE(You can use additional labels at the end)
#
move $a3,$s0
move $a1,$s1
add $a3,$a3,$a1
la $a2, output($zero)
jal reverse
la $a0,msg3
li $v0,4
syscall
la $a0,output($zero)
li $v0,4
syscall
li $v0,10
syscall
reverse:
# $a0 - address of string to reverse
# a1 - length of the string
# a2 - address of string where to store the reverse
addi $sp, $sp, -4
sw $ra, 0($sp)
bltz $a1, reverse_end
lb $t0, 0($a3)
subi $a1, $a1, 1
subi $a3, $a3, 1
sb $t0, 0($a2)
addi $a2, $a2, 1
jal reverse
reverse_end:
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
编辑:这也是回文生成的 C++ 实现。
回文生成递归算法的C++实现
#include <iostream>
#include <string>
using namespace std;
string palindrom(string input, int rem_length)
{
if(rem_length!=0)
{
input=input.substr(0,1)+palindrom(input.substr(1,input.length()-1), \\
rem_length-1)+input.substr(0,1);
}
return input;
}
int main()
{
string input;
cin >> input;
input = palindrom(input, input.length());
cout << input<< endl;
system("pause");
return 0;
}
【问题讨论】: