1、利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“1ab4c2a”。若压缩后的字符串没有变短,则返回原先的字符串
int mian()
{
string a;
getline(cin,a);
int i=0;
while(a[i]!='\0')
{
i++;
}
string res;
int count =1;
for(int i=0;i<a.length()-1;i++)
{
if(a[i]==a[i+1])
{
count++;
if(i==a.length()-2)
{
res.push_back(count+'0');
res.push_back(a[i]);
}
}
else
{
if(count>1)
{
res.push_back(count+'0');
}
count=1;
res.push_back(a[i]);
if(i+1==a.length()-1)
res.push_back(a[i+1]);
}
}
cout<<res;
return 0;
}
大佬的
#include <iostream>
#include <vector>
#include <cmath>
#include <map>
using namespace std;
int main()
{
string str;
cin >> str;
string res;
int start = 0;
int end = 0;
for(int i = 0; i < str.size()-1; ++i)
{
start = end = i;
while (str[i+1] == str[i])
{
++i;
}
end = i;
int len = end- start+1;
res += to_string(len) + str[start];
}
cout << res <<endl;
return 0;
}
2、输入某二叉树的层序遍历和中序遍历的结果,请重建出该二叉树,输出左向叶子节点 前序遍历 后序遍历。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入层序遍历序列{3 5 4 2 6 7 1}和中序遍历序列{2 5 3 6 4 7 1},则重建二叉树并返回 左向叶子{ 2 6 7} 前序{ 3 5 2 4 6 7 1}后序{2 5 6 1 7 4 3}。
#include <bits/stdc++.h>//包含所有文件
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
//TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<int> layer,in;
void preorder(TreeNode* root)
{
if(root!=nullptr)
{
cout<<root->val<<" ";
preorder(root->left);
preorder(root->right);
}
}
void postorder(TreeNode* root)
{
if(root!=nullptr)
{
postorder(root->left);
postorder(root->right);
cout<<root->val<<" ";
}
}
void leaf(TreeNode* root)
{
if(root!=nullptr)
{
if(root->left==NULL&&root->right==NULL)
cout<<root->val<<" ";
leaf(root->left);
leaf(root->right);
}
}
void inorder(TreeNode *root)
{
if(root!=nullptr)
{
inorder(root->left);
cout<<root->val<<" ";
inorder(root->right);
}
}
//层序 中序构建二叉树
TreeNode* reConstructBinaryTree(int ll,int lr,int li,int ri)
{
if(li>ri)return NULL;
TreeNode* BtreeNode=new TreeNode;
//BtreeNode->val=layer[0];
//int i=0;
//for(;i<in.size()&&in[i]!=layer[0];i++);
int i,j;
bool f;
for(i=ll;i<=lr;i++)
{
f=false;
for(j=li;j<=ri;j++)
{
if(layer[i]==in[j])
{
BtreeNode->val=in[j];
BtreeNode->left=NULL;
BtreeNode->right=NULL;
f=true;
break;
}
}
if(f)break;
}
if(!f)return NULL;
if(j>li)BtreeNode->left=reConstructBinaryTree(0,layer.size()-1,li,j-1);
if(j<ri)BtreeNode->right=reConstructBinaryTree(0,layer.size()-1,j+1,ri);
return BtreeNode;
}
int main( )
{
string s;
getline(cin,s);
istringstream is(s);
int t;
char c;
while(is>>t)
{
//is>>c;
layer.push_back(t);
}
getline(cin,s);
istringstream is1(s);
while(is1>>t)
{
in.push_back(t);
}
if(layer.size()!=in.size()||in.empty())return 0;
TreeNode* BtreeNode=new TreeNode;
BtreeNode->val=layer[0];
int tlen = layer.size();
TreeNode *root = reConstructBinaryTree(0,layer.size()-1,0,in.size()-1);
leaf(root);
cout<<endl;
preorder(root);
cout<<endl;
postorder(root);
return 0;
}
3.LeetCode 233.数字1的个数 Number of Digit One