替换空格
题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。
思路:
首先 我们确认好题目是在原来的一个字符串上加长还是新建字符串,问面试官,
假设在原来的字符串上加长,有两种解法,1从头扫到尾,时间复杂度为O(n*n)2.反向思考,从尾部开始填充,
即,先遍历一次字符组,统计字符串中空格数目以及字符串总长度,然后我们从尾部开始复制,准备两个指针,一个指向原字符串末尾,一个指向替换之后的字符串的尾部,遇空格第二个指针移3格,否则移一格。
#include<iostream>
#include<cstring>
using namespace std;
void rep(char str[],int l){
if(str == nullptr ||l <=0)
return ;
int orignlength = 0;
int numberblank = 0;
while(str[orignlength++] != '\0'){
if(str[orignlength] == ' ')
++numberblank;
// ++orignlength;
}
int newlength =orignlength + 2*numberblank;
if(newlength > l)
return ;
int indexorign = orignlength;
int indexnew = newlength;
while(indexorign >0 && indexnew > indexorign){
if(str[indexorign] == ' ') {
str[indexnew--] = '%';
str[indexnew--] = '2';
str[indexnew--] = '0';
}else{
str[indexnew--] = str[indexorign];
//cout<< str[indexnew] ;
}
--indexorign;
}
}
int main(){
char string1[]="we are happy!";
rep(string1,20);
cout << string1;
return 0;
}
二维数组查找
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
例如下面的二维数组就是每行、每列都递增排序。如果在这个数组中查找数字7,则返回true;如果查找数字5,由于数组不含有该数字,则返回false。
二、解题思路
1.。首先选取数组中右上角的数字。如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,剔除这个数字所在的列;如果该数字小于要查找的数字,剔除这个数字所在的行。也就是说如果要查找的数字不在数组的右上角,则每一次都在数组的查找范围中剔除一行或者一列,这样每一步都可以缩小查找的范围,直到找到要查找的数字,或者查找范围为空。(也可以选取左下角的数字,本代码选取左下角数字)
#include<iostream>
#include<cstring>
using namespace std;
bool finde(int matrix[][100],int rows,int columns,int number){
bool found = false;
if(matrix != nullptr && rows > 0 && columns >0){
int row = rows - 1;
int column =0;
while(row >= 0 && column < columns){
if(matrix[row][column] == number){
found = true;
break;
}else if(matrix[row][column] > number){
--row;
}else
++column;
}
}
return found;
}
int main(){
int rows,columns,number;
cin>> rows >> columns >> number;
int matrix[100][100] = {0};
for(int i=0;i<rows;++i){
for(int j=0;j<columns;++j)
cin >> matrix[i][j];
}
cout << finde(matrix,rows,columns,number);
return 0;
}