- Buy Fruits
Xiao Ming is going to help companies buy fruit. Give a codeList, which is loaded with the fruit he bought. Give a shoppingCart, which is loaded with target fruit. We need to check if the order in the codeList matches the order in the shoppingCart. Note that only the sum of the items in all linked lists in the codeList add up to less than or equal to the sum of items in the shoppingcart may return 1. In addition, the item in codeList may be “anything”, which can match with any fruit.
Example
Example 1:
Input: codeList = [[“apple”, “apple”],[“orange”, “banana”, “orange”]], shoppingCart = [“orange”, “apple”, “apple”, “orange”, “banana”, “orange”]
Output: 1
Explanation: Because the order in the codeList matches the fruit in the shoppingCart except for the first orange.
Example 2:
Input: codeList = [[“orange”, “banana”, “orange”],[“apple”, “apple”]], shoppingCart = [“orange”, “apple”, “apple”, “orange”, “banana”, “orange”]
Output: 0
Explanation: Because the order in the codeList doesn’t match the shoppingCart.
Example 3:
Input: codeList = [[“apple”, “apple”],[“orange”, “anything”, “orange”]], shoppingCart = [“orange”, “apple”, “apple”, “orange”, “mango”, “orange”]
Output: 1
Explanation: anything matches mango, so codeList can match the fruit of shoppingCart.
Notice
The number of fruits in codeList and the number of fruits in shppingCart are both less than 2000.
解法1:
一开始没看懂题目意思。看了答案才知道其实就是挨个比较,遇到"anything"也算是match。
注意:
- shopping cart一开始可能会包含一些无关的item,需要挨个从头开始检查。
class Solution {
public:
/**
* @param codeList: The codeList
* @param shoppingCart: The shoppingCart
* @return: The answer
*/
int buyFruits(vector<vector<string>> &codeList, vector<string> &shoppingCart) {
int m = codeList.size();
vector<string> singleList;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < codeList[i].size(); ++j) {
singleList.push_back(codeList[i][j]);
}
}
if (singleList.size() > shoppingCart.size()) return 0;
for (int i = 0; i + singleList.size() <= shoppingCart.size(); ++i) {
for (int j = 0; j < singleList.size(); ++j) {
if (singleList[j] != shoppingCart[i + j] && singleList[j] != "anything") break;
if (j == singleList.size() - 1) return 1;
}
}
return 0;
}
};
代码同步在
https://github.com/luqian2017/Algorithm
本文介绍了一种用于检查购物清单是否符合预设代码列表的算法,特别适用于水果购买场景。算法考虑了特殊通配符'anything',允许其匹配任意水果。
254

被折叠的 条评论
为什么被折叠?



