1、猫狗队列
实现一种狗猫队列的结构,要求如下:
用户可以调用add方法将cat类或dog类的实例放入队列中;
用户可以调用pollAll方法,将队列中所有的实例按照进队列的先后顺序依次弹出;
用户可以调用pollDog方法,将队列中dog类的实例按照进队列的先后顺序依次弹出;
用户可以调用pollCat方法,将队列中cat类的实例按照进队列的先后顺序依次弹出;
用户可以调用isEmpty方法,检查队列中是否还有dog或cat的实例;
用户可以调用isDogEmpty方法,检查队列中是否有dog类的实例;
用户可以调用isCatEmpty方法,检查队列中是否有cat类的实例。
自己的思路:
用三个队列,分别存储cat、dog和全体。去听一下左神有什么好办法。
左神的思路:
左神做了一个结构体,结构体里面存储宠物的类型和宠物进入队列的顺序编号。这样,用两个队列就可以满足情况了。(我的想法被否定了)
实现代码写出来了,贼开心~
#include<iostream>
#include<queue>
#include<string>
using namespace std;
struct animal {
string name;
int index;
string getName(animal input) const { return input.name; }
};
class CatAndDog {
public:
CatAndDog(int i = 0):index(i) {}
void add(string input);
void pollAll();
void pollDog();
void pollCat();
bool isEmpty();
bool DogEmpty();
bool CatEmpty();
private:
queue<animal>cat, dog;
int index;
};
ostream& operator<<(ostream& os, const animal& str)
{
os << str.getName(str);
return os;
}
void CatAndDog::add(string input) {
if (input.length() == 0) return;
animal animalInput;
animalInput.name = input;
animalInput.index = index++;
if (input[0] == 'c') {
cat.push(animalInput);
}
else {
dog.push(animalInput);
}
}
void CatAndDog::pollAll() {
while (!cat.empty() && !dog.empty()) {
if (cat.front().index < dog.front().index) {
cout << cat.front() << endl;
cat.pop();
}
else {
cout << dog.front() << endl;
dog.pop();
}
}
while (!cat.empty()) {
cout << cat.front() << endl;
cat.pop();
}
while (!dog.empty()) {
cout << dog.front() << endl;
dog.pop();
}
index = 0;
}
void CatAndDog::pollDog() {
while (!dog.empty()) {
cout << dog.front() << endl;
dog.pop();
}
}
void CatAndDog::pollCat() {
while (!cat.empty()) {
cout << cat.front() << endl;
cat.pop();
}
}
bool CatAndDog::isEmpty() {
if (cat.empty() && dog.empty()) return true;
else return false;
}
bool CatAndDog::DogEmpty() {
if (dog.empty()) return true;
else return false;
}
bool CatAndDog::CatEmpty() {
if (cat.empty()) return true;
else return false;
}
int main() {
CatAndDog god;
/*
void add(string input);
void pollAll();
void pollDog();
void pollCat();
bool isEmpty();
bool DogEmpty();
bool CatEmpty();
*/
string input;
int n = 10;
while (n--) {
cin >> input;
god.add(input);
}
bool em=god.isEmpty();
bool dogg= god.DogEmpty();
bool ca= god.CatEmpty();
god.pollDog();
god.pollCat();
god.pollAll();
bool emm = god.isEmpty();
bool doggg = god.DogEmpty();
bool caa = god.CatEmpty();
return 0;
}
2、转圈打印矩阵
不要把思路限制在局部,跟着遍历的方向去移动。
我们记录左上角的点和右下角的点,这里记左上角为(a,b),右下角为(c,d)。
如果只是打印上面的矩形的边,还是很容易的。
如果b和d在同一行,那就是,这是一种边界条件,
如果a和c相同,则,这也是一种边界条件。
打印边的方式,可以通过while循环来实现,四个while循环分别绘制的图形如图:
实现了一个能够打印矩形框的函数之后,然后我们可以调用他打出整个的矩阵,调用思路如图:
每次打印完一个矩形,左上角的点向右下方移动一个格子,同理,右上角的点向左上方移动一个格子。
解题时,要有一个宏观的感觉。不要把思路局限在问题怎么变上。
判断括号中字符串是否有效果
返回数据流中第k大元素
滑动窗口中的最大值(leetcode)