所有代码都在github
11.数字颠倒
颠倒就是逆序,可以把数字to_string
一下然后再reserve
我的做法是按数字的方式处理,模10除10
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
string str;
while(n)
{
str+=to_string(n%10);
n/=10;
}
cout<<str<<endl;
}
return 0;
}
12.字符串翻转
利用STL逆向迭代器和构造函数搞定
#include <iostream>
#include <string>
using namespace std;
int main()
{
string n;
while(getline(cin,n))
{
string str(n.rbegin(),n.rend());
cout<<str<<endl;
}
return 0;
}
13.句子逆序
"hello world"
变成"world hello"
这个要逆转两次,先对整个句子进行逆序
"dlrow olleh"
再逐个单词逆序
"world hello"
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string line;
while(getline(cin,line))
{
string tmp(line.rbegin(),line.rend());
stringstream ss(tmp);
string word;
vector<string>words;
while(ss>>word)
{
words.push_back(string(word.rbegin(),word.rend()));
words.push_back(" ");
}
for(int i=0;i<words.size();++i)
{
if(i==words.size()-1)
words[i].pop_back();
cout<<words[i];
}
cout<<endl;
}
return 0;
}
14.字串的连接最长路径查找
看完题目才知道是字符串字典序排序,直接上std::sort
也行
不过我用了优先级队列,这样的话复杂度应该低一些。
std::priority_queue
需要注意的是模板参数
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
int main()
{
int n;
priority_queue<string,vector<string>,greater<string> >q;
string str;
while(cin>>n)
{
for(int i=0;i<n;++i)
{
cin>>str;
q.push(str);
}
while(!q.empty())
{
cout<<q.top()<<endl;
q.pop();
}
}
return 0;
}
15.求int型正整数在内存中存储时1的个数
剑指offer上的题,有一个小小的trick吧,当然直接按位比较也行的
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int count=0;
while(n)
{
n&=(n-1);
++count;
}
cout<<count<<endl;
}
}
16.购物单
这应该是前20题里面最耗费我时间的一题了。
改进的0-1背包,先回顾一下0-1背包:
最朴素的0-1背包问题里面,只有拿和不拿两个选项
因此动规方程可以如下写:
dp(i,j)=max(d