Day4
描述
接受一个只包含小写字母的字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
输入描述:
输入一行,为一个只包含小写字母的字符串。
输出描述:
输出该字符串反转后的字符串。
示例1
输入:
abcd
复制
输出:
dcba
思路:
- 法1:直接逆序遍历,String类型字符
- 法2:利用栈,将字符输入到栈里面,然后对栈进行遍历
- 法3:双指针原地交换算法,直接双指针,遍历的同时,两头进行交换,直到两指针相遇为止
复杂度:
- 法1:时间复杂度O(n),空间复杂度O(1)
- 法2:时间复杂度O(2n),空间复杂度O(n),多出一个栈空间
- 法3:时间复杂度O(n),空间复杂度O(1)
具体思路
#include <math.h>
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <cstring>
//#include "./include/list/sqlist.h"
using namespace std;
//day4
//接受一个只包含小写字母的字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
//法1:逆向输出法,非原地算法
/**
* @description: O(n)+O(n)
* @param {string} s
* @return {*}
*/
void ReverseString(string s){
//string ans;
int len_s = s.length();
for(int i = len_s - 1, j = 0; i >= 0; i--){
printf("%c",s[i]);
}
}
//法2:使用栈,因为所有逆向输出都可用栈
/**
* @description: O(n)+O(n),增加额外的栈空间
* @param {string} s
* @return {*}
*/
void ReverseStringII(string s){
int len_s = s.length();
stack<char> c_stack;//字符栈
int i = 0;
for(int i = 0; i < len_s; i++){
c_stack.push(s[i]);
}
while(!c_stack.empty()){
char c_temp = c_stack.top();
c_stack.pop();
printf("%c",c_temp);
}
}
//法3:迭代交换法
/**
* @description:
* @param {string} &s
* @return {*}
*/
void ReverseStringIII(string &s){
int left = 0;//左指针
int right = s.length()-1;//右指针
while(left < right){
//直接依次交换
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
//然后遍历原串,直接输出
for(int i = 0; i < s.length(); i++){
printf("%c",s[i]);
}
}
int main(){
string s;
//用到getline
getline(cin,s);//将输入流直接赋给s字符串
//char c;
//cin >> c;
//int lastans = CountDifferentCharacter(s);
ReverseString(s);
//printf("%d",lastans);
system("pause");
return 0;
}
小结
- 题目要求是遍历输出,如果改为是修改字符串,那么双指针法比较好,空间复杂度为O(1)