Buckle 344. reverse string

Buckle 344. reverse string

https://leetcode-cn.com/problems/reverse-string/

Write a function whose function is to reverse the input string. The input string is given as a character array char [].

Don't allocate extra space to another array, you must modify the input array in place and use O (1) extra space to solve this problem.

You can assume that all characters in the array are printable characters in the ASCII code table.

 

Double pointer method

Complexity analysis

Time complexity: O (N). N / 2N / 2 exchanges were performed.
Space complexity: O (1), only constant-level space is used.

#include "stdafx.h"
#include<vector>
using namespace std;
class Solution {
public:
	void reverseString(vector<char>& s) 
	{
		//双指针法
		int i = 0;
		int j = s.size() - 1;
		while (i<j)//首尾交换,直到i>=j
		{
			char temp = s[i];
			s[i] = s[j];
			s[j] = temp;
			i++;
			j--;
		}
	}
};


int main()
{
	Solution str;
	vector<char> s;
	s.push_back('h'); s.push_back('e'); s.push_back('l'); s.push_back('l'); s.push_back('o');
	vector<char> s1;
	s1.push_back('H'); s1.push_back('a'); s1.push_back('n'); s1.push_back('n'); s1.push_back('a'); s1.push_back('h');
	str.reverseString(s);
	str.reverseString(s1);
    return 0;

The double-pointer method uses two pointers, a left pointer left and a right pointer right. When starting work, left points to the first element, and right points to the tail element. Swap the elements pointed by the two pointers and move to the middle until the two pointers meet.

algorithm:

Point left to the first element and right to the end element.
When left <right:
exchange s [left] and s [right].
left ++
right ++

Insert picture description here

 

Published 23 original articles · praised 0 · visits 137

Guess you like

Origin blog.csdn.net/qq_35683407/article/details/105420081