leetcode刷题9天
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
class Solution {
public int strStr(String haystack, String needle) {
if(haystack.equals(needle))
return 0;
if(haystack.length()<needle.length())
return -1;
int i;
boolean flag = false;
for(i = 0;i<haystack.length();i++) {
//System.out.println(i+needle.length());
if(i+needle.length()<=haystack.length()&&haystack.substring(i,i+needle.length()).equals(needle)) {
//System.out.println(true);
flag = true;
break;
}
}
if(flag)
return i;
else
return -1;
}
}
- Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
代码:
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length==0)
return 0;
if(nums[0]>=target)
return 0;
int i ;
for(i =0;i<nums.length-1;i++) {
if(nums[i]<target&&nums[i+1]>=target) {
//System.out.println(true);
break;
}
}
return i+1;
}
}
-
Count and Say
The count-and-say sequence is the sequence of integers with the first five terms as following: -
1
-
11
-
21
-
1211
-
111221
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
class Solution {
public String countAndSay(int n) {
if(n == 1)
return "1";
String prestr = countAndSay(n-1)+"#";
char[] c = prestr.toCharArray();
int count = 1;
String res ="";
for(int i = 0; i < prestr.length() - 1;i++){
if(prestr.charAt(i) == prestr.charAt(i+1))
count++;
else{
res = res + count + prestr.charAt(i);
count = 1;
}
}
return res;
}
}