JZ2——替换空格
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
string replaceSpace(string s) {
// write code here
string res;
for(auto it = s.begin(); it != s.end(); it++)
{
if( ! isspace(*it) )
res += *it;
else
res += "%%";
}
return res;
}
};
JZ44——翻转单词顺序列
注:注意一些特殊情况
class Solution {
public:
string ReverseSentence(string str) {
string res;
string temp;
int i = 0;
for(auto it = str.cbegin(); it != str.cend(); it++)
{
if( !isspace(*it))
temp += *it;
else{
i++;
if(i == 1)
res = temp;
else
res = temp + " " + res;
temp.clear();
}
}
i++;
if(i == 1)
res = temp;
else
res = temp + " " + res;
return res;
}
};
JZ45——扑克牌顺子
思路:
满足两个条件
1. 除了0之外没有重复的数
2. max - min <= 4
class Solution {
public:
int max = -1, min = 14;
map<int,int> count;
bool IsContinuous( vector<int> numbers ) {
if(numbers.size() == 0)
return false;
for(auto it : numbers)
{
count[it]++;
if(count[it] > 1 && it!= 0)
return false;
if(it < min && it != 0)
min = it;
if(it > max)
max = it;
}
if(max - min > 4)
return false;
else
return true;
}
};
/*思路:
满足两个条件
1. 除了0之外没有重复的数
2. max - min <= 4
*/
JZ49——把字符串转换成整数
**主要考虑的几个点
- 首位是不是 ‘+’ ‘-’ 符号,并考虑对结果的影响
- 首位是不是字母,若是直接返回0
- 中间是否出现字母,一旦出现字母立刻返回0**
class Solution {
public:
int StrToInt(string str) {
int len = str.size();
int flag = 1;
int res = 0;
if(len == 0)
return 0;
if(str[0] == '+')
flag = 1;
else if(str[0] == '-')
flag = -1;
else if(isalpha(str[0]))
return 0;
else
res = str[0] - '0';
for(int i = 1; i < len; i++)
{
if(isalpha(str[i]))
return 0;
else
res = res * 10 + (str[i] - '0');
}
return flag*res;
}
};
JZ54——字符流中第一个不重复的字符
使用map可以很简单的解决
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch) {
str.push_back(ch);
count[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce() {
for(int i = 0; i < str.size(); i++){
if(count[str[i]] == 1)
return str[i];
}
return '#';
}
private:
string str;
map<char,int> count;
};