1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 int big = haystack.length(); 4 int sub = needle.length(); 5 if(big==0 && sub==0) return 0; 6 if(big==0 && sub!=0) return -1; 7 int index = big-sub; 8 for(int i=0;i<=index;i++){ 9 if(haystack.substring(i,sub+i).equals(needle))return i; 10 } 11 return -1; 12 } 13 }
是int index = haystack.indexOf(needle)的另一种做法
Climbing Stairs
1)递归调用(容易内存溢出):
1 public class Solution { 2 public int climbStairs(int n) { 3 if(n<1)return 0; 4 if(n==1)return 1; 5 if(n==2)return 2; 6 return climbStairs(n-1)+climbStairs(n-2); 7 } 8 }
2)类似斐波那契数列,开头1,2.代替1.1
1 public class Solution { 2 public int climbStairs(int n) { 3 if(n<1)return 0; 4 if(n==1)return 1; 5 if(n==2)return 2; 6 int nums = 0; 7 int one = 1; 8 int two = 2; 9 for(int i=3;i<=n;i++){ 10 nums = one+two; 11 one = two; 12 two = nums; 13 } 14 return nums; 15 } 16 }
https://leetcode.com/problems/climbing-stairs/#/description