Reverse String
摘要
本次内容主要是对LeetCode网站上算法题目分类下的Reverse String一题提供一些个人的解决方案,用于完成个人在算法设计与分析课程的学习任务。
题目描述与分析
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
题目要求为输入一个字符串,通过代码实现输出该字符串的逆序,比如输入字符串“hello”,输出结果为“olleh”。
题目解决方案与分析
方案一: 直接逆序(for循环)
实现一个字符串的逆序,可以直接将目标字符串从末端到前端的字符依次添加到一个空字符串的末端(即从后到前),最后得到的字符串就是结果字符串。该过程使用了一个for循环,代码如下:
//reverseString1.cpp-使用for循环直接逆序
#include <iostream>
#include <cstring>
using namespace std;
string reverseString(string s);
int main()
{
string S = "hello";
cout << reverseString(S) << endl;
return 0;
}
string reverseString(string s)
{
string N =