Written test training Day3

Table of contents

1. Sort subsequences

2. Invert the string


Tip: The solutions to these two questions need to use the knowledge points of STL

1. Sort subsequences

 Idea: The sorted subsequence in a string of arrays actually refers to the non-decreasing or non-increasing part of the subsequence . The two numbers before and after being equal will actually change whether the subsequence is increasing or decreasing. This may make many Classmates are tangled.

To give a few examples:

1 2 3 3 2 1, you can split it into 123|321 or 1233|21 or 1233|21 We can see that the two numbers are equal without changing the result. Can only be split into two. 

Code:

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	int n;
	int count = 0;
	cin >> n;
	vector<int> a;
	a.resize(n+1);//多申请一个空间避免越界
	a[n] = 0;
	for(int i=0;i<n;i++)
	{
		cin >> a[i];
	}
	int i = 0;
	while (i < n)//在循环中判断是增是减,并进行i的后移,当i>=n时循环结束
	{
		//在这里上面给a多申请的一个空间就起作用了,避免a[i+1]越界
		if (a[i] < a[i + 1])
		{
			//防止a[i+1]越界
			while (i<n&&a[i] <= a[i + 1])
			{
				i++;
			}
			count++;
            i++;//结束了就去判断下一个排序子序列
		}
        //当前后相等时不影响结果
		else if (a[i] == a[i + 1])
		{
			i++;
		}
        //与上面同理
		else
		{
			while (i<n&&a[i] >= a[i + 1])
			{
				i++;
			}
			count++;
			i++;
		}
	}
	cout << count;
	return 0;
}

2. Invert the string

 Idea: We can invert the entire string, and then invert each word once to achieve this goal

answer:

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
	string s;
	getline(cin, s);
	reverse(s.begin(), s.end());
	auto start = s.begin();
	auto end = s.end();
	while (start < s.end())
	{
		end = start;
		while (end < s.end() && *end!=' ')
		{
			end++;
		}
		reverse(start, end-1);
		if (end!=s.end())
		{
			start = end + 1;
		}
		else
		{
			start = end;
		}
	}
	cout << s;
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_64484137/article/details/128351825