leetcode笔记 28. Implement strStr() & 35. Search Insert Position & 38. Count and Say

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;
    }
}
  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;
    }
}
  1. Count and Say
    The count-and-say sequence is the sequence of integers with the first five terms as following:

  2. 1
    
  3. 11
    
  4. 21
    
  5. 1211
    
  6. 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;     
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值