现在开始要好好学习了,开始利用写博客记录学习内容、过程和思路。
问题出自https://leetcode.com/problems/reverse-string/ 字符串反转问题。
上述是一个很好的练习算法、编程的网站
问题描述
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
该问题要求反转字符串。
我这里提出了两种思路
(1)新建一个字符串,将原字符串一个个倒序赋值给新字符串
class Solution {
public:
string reverseString(string s) {
string str2=s;
int nlen=s.size();
for(int i=0;i<nlen;i++)
{str2[i]=s[nlen-i-1];}
return str2;
}
};
(2)第二种思路是直接在原序列中交换第i个和第s.size()-i个的位置,循环s.size()/2次
class Solution {
public:
string reverseString(string s) {
int temp;
int n=s.size();
for(int i=0;i<n/2;i++)
{temp=s[i];
s[i]=s[n-i-1];
s[n-i-1]=temp;
}
return s;
}
};
注意int i是从0开始。
这道题在leetcode算简单的题。下次打算学习STL,对string、vector等不是很熟,string很多功能比char要方便。打好基础很重要!