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);
}
}
}