[LintCode] Buy Fruits

本文介绍了一种用于检查购物清单是否符合预设订单序列的算法。该算法通过比较两个列表——预设订单序列(codeList)与实际购物清单(shoppingCart),判断实际购物清单是否至少包含预设订单序列的所有元素及顺序。

Problem

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.

Notice

The number of fruits in codeList and the number of fruits in shppingCart are both less than 2000.

Example

Given codeList = [["apple", "apple"],["orange", "banana", "orange"]],, shoppingCart = ["orange", "apple", "apple", "orange", "banana", "orange"], return 1.

Explanation:

Because the order in the codeList matches the fruit in the shoppingCart except for the first orange.

Given codeList = [["orange", "banana", "orange"],["apple", "apple"]], shoppingCart = ["orange", "apple", "apple", "orange", "banana", "orange"], return 0.

Explanation:

Because the order in the codeList doesn't match the shoppingCart.

Given codeList = [["apple", "apple"],["orange", "anything", "orange"]], shoppingCart = ["orange", "apple", "apple", "orange", "mango", "orange"], return 1.

Explanation:

anything matches mango, so codeList can match the fruit of shoppingCart.

Solution


public class Solution {
    /**
     * @param codeList: The codeList
     * @param shoppingCart: The shoppingCart
     * @return: The answer
     */
    public int buyFruits(List<List<String>> codeList, List<String> shoppingCart) {
        // Write your code here
        List<String> mingList = new ArrayList<>();
        for (List<String> list: codeList) {
            for (String str: list) {
                mingList.add(str);
            }
        }
        
        if (mingList.size() > shoppingCart.size()) return 0;
        
        for (int i = 0; i <= shoppingCart.size()-mingList.size(); i++) {
            for (int j = 0; j < mingList.size(); j++) {
                String cur = mingList.get(j);
                if (cur.equals(shoppingCart.get(i+j)) || cur.equals("anything")) {
                    if (j == mingList.size()-1) return 1;
                    else continue;
                } else {
                    break;
                }
                
            }
        }
        
        return 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值