/**
算法思想:遍历输入流,将符号和数字分开存到两个数组里,减号作为数字的负数。
然后在符号集里面找*或者/,找到就把对应的数组集两个操作数比较并排序。
然后数组被分割成三段,中间是乘法和两个交换数,两边是没有操作的数据,然后分别对两边做递归。
如果没有找到*或者/说明全是加法,直接对数组的数据进行排序。
*/
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
/**
6
1 + 2 + 1 + -4 * -5 + 1
1 + 1 + 2 + -5 * -4 + 1
*/
int data[100];
char fuhao[100];
/**
* 快排序
* @param a
* @param low
* @param high
*/
void quickSort(int a[], int low ,int high)
{
if(low<high)
{
int i = low, j = high;
int x = a[low];
while(i<j)
{
while(i<j && a[j] >= x) j--;
if(i<j) a[i++] = a[j];
while(i<j && a[i] <= x) i++;
if(i<j) a[j--] = a[i];
}
a[i] = x;
quickSort(a, low ,i-1);
quickSort(a, i+1 ,high);
}
}
void mySort(int data[], char fuhao[], int begin, int end){
for (int i = begin; i < end; ++i) {
if (fuhao[i] == '*' || fuhao[i] == '/'){
// 先对乘除两边进行排序
if (data[i] > data[i+1]){
int temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
}
mySort(data, fuhao, begin, i-1);
mySort(data, fuhao, i+2, end);
return;
}
}
// 没有乘除号,就对+-的数字进行排序
quickSort(data, begin, end);
}
int main() {
int n = -1;
char temp;
int size_data = 0;
int size_fuhao = 0;
scanf("%d", &n);
getchar();
scanf("%c", &temp);
int num = 0;
bool munes = false;
while (temp != '\n'){
if (temp == '+' || temp == '*' || temp == '/'){
// 添加数字
if (munes){
num = -num;
}
data[size_data++] = num;
num = 0;
munes = false;
// 添加符号
fuhao[size_fuhao++] = temp;
}
else if (temp >= '0' && temp <= '9'){
num = num*10 + temp - '0';
} else if (temp == '-'){
// 遇见负号
munes = true;
}
scanf("%c", &temp);
}
data[size_data++] = num;
mySort(data, fuhao, 0, size_data-1);
for (int i = 0; i < size_data - 1; ++i) {
printf("%d", data[i]);
printf("%c", fuhao[i]);
}
cout<< data[size_data-1];
return 0;
}
滴滴面试题第一道
最新推荐文章于 2021-03-02 05:09:40 发布