[LintCode] 1. strStr

LintCode Ladder 1 - strStr

1. strStr (LeetCode 28)

For a given source string and a target string, you should output the first index(from 0) of target string in source string.
If target does not exist in source, just return -1.

for循环做法(from LintCode Solution)

class Solution {
    public int strStr(String source, String target) {
        if (source == null || target == null) {
            return -1;
        }

        if (target == "") {
            return 0;
        }

        for (int i = 0; i < source.length() - target.length() + 1; i++) {
            for (int j = 0; j < target.length(); j++ ) {
                if (source.charAt(i + j) != target.charAt(j)) {
                    break;
                }

                if (j == target.length() - 1) {
                    return i;
                }
            }
        }
        return -1;
    }
}

2. Subsets (LeetCode 78)

Given a set of distinct integers, return all possible subsets.

非递归做法(from Code Ganker):
对于res,把之前已经加入进res的每个item,都再加上新的元素,组成集合,加入res里

class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {  
         ArrayList<ArrayList<Integer>> res = new  ArrayList<ArrayList<Integer>>();  
         res.add(new ArrayList<Integer>());  
         if(S == null || S.length == 0)  
            return res;  
        Arrays.sort(S);  
        for(int i=0;i<S.length;i++)  
        {  
            int size = res.size();  
            for(int j=0;j<size;j++) //先从里层的for循环写起,再套上外层
            {  
                ArrayList<Integer> item = new ArrayList<Integer>(res.get(j));  
                item.add(S[i]);  
                res.add(item);  
            }  
        }  
        return res;  
    }  
}

递归做法(from LintCode Solution):
经典DFS问题,对于输入里的每一个元素,都放到子集合,添加元素,添加进res,如果后面还有元素,接着添加元素,添加进res,再backtrack

class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> item = new ArrayList<Integer>();

        if(num == null || num.length == 0) {
            return res;
        }

        Arrays.sort(num);  
        subsetsHelper(res, item, num, 0);

        return res;
    }

    private void subsetsHelper(ArrayList<ArrayList<Integer>> res,
        ArrayList<Integer> item, int[] num, int pos) {

        res.add(new ArrayList<Integer>(item));

        for (int i = pos; i < num.length; i++) {
            item.add(num[i]); 
            subsetsHelper(res, item, num, i + 1);
            item.remove(item.size() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值