剑指 2 替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str == nullptr||length<=0)
return;
//统计整个字符串的长度
int orlength = 0;
int blanklength = 0;
int i;
for(int i=0;str[i] !='\0';i++)
{
orlength ++;
if (str[i] ==' ')
{
blanklength++;
}
}
int newlength = orlength + blanklength*2;
if(newlength>length)
return;
int indexofnew = newlength;
int indexofor = orlength;
while(indexofnew>indexofor )
{
if(str[indexofor] == ' ')
{
str[indexofnew--] = '0';
str[indexofnew--] = '2';
str[indexofnew--] = '%';
}
else
{
str[indexofnew--] = str[indexofor];
}
indexofor--;
}
}
};
剑指34 第一个只出现一次的字符位置
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int length = str.size();
// if(length <= 0){
// return -1;
// }
int count[256] = {0};
for (int i=0;i<str.size();i++)
{
count[str[i]]++;
}
for(int i = 0;i<str.size();i++)
{
if(count[str[i]] == 1)
return i;
}
return -1;
}
};
剑指43左旋转字符串
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
class Solution {
public:
string LeftRotateString(string str, int n) {
//ab cdefg
//ba gfedc
//cdefg ab
//先统计字符串长度
int i = 0;
int length = 0;
while(str[i] !='\0')
{
length++;
i++;
}
if (length>0&&n<length)
{
reverse(str.begin(), str.begin()+n);
reverse(str.begin()+n, str.end());
reverse(str.begin(), str.end());
}
return str;
}
};
剑指45 扑克牌顺子
题目描述
五张牌判断是不是顺子
0可以替代任何数字
class Solution {
public:
bool IsContinuous( vector<int> numbers ) {
//1.先排序
if(numbers.empty())
return false;
sort(numbers.begin(), numbers.end());//排序
int num0 = 0;
int blank = 0;
int temp = 0;
for(int i =0;i<numbers.size()-1;i++)
{
if(numbers[i]!= 0 && numbers[i] == numbers[i+1])
{
return false;
}
if(numbers[i] ==0)
{
num0 ++;
}
if(numbers[i]!=0 && numbers[i+1]-numbers[i]>=2)
{
temp = numbers[i+1] -numbers[i]-1;
blank +=temp;
}
}
if (num0 < blank)
return false;
else
return true;
}
};