13. 字符串查找

13. Implement strStr()

Description

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.

Clarification

Do I need to implement KMP Algorithm in a real interview?

  • Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure you confirm with the interviewer first.

Example

If source = "source" and target = "target", return -1.

If source = "abcdabcdefg" and target = "bcd", return 1.

Challenge

O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: KMP)

class Solution {
    /**
     * @param source: 
     * @param target: 
     * @return: return the index
     */
    public int strStr(String source, String target) {
        // Write your code here
//    	return source.indexOf(target);
    	if(source.length() < target.length()) {
    		return -1;
    	}
    	if(target == "" || source.equals(target)) {
    		return 0;
    	}
    	
    	boolean res = true;
    	int sou = source.length();
    	int tar = target.length();
    	for(int i=0;i < sou -tar +1;i++) {
    		
    		for(int j = 0,k=i ;j<tar ;j++,k++) {
    			if(source.charAt(k) != target.charAt(j)) {
    				res = false;
    				break;
    			}
    			
    		}
    		
    		if(res) {
    			return i;
    		}
    		res = true;
    		
    	}
    	
    	return -1;	

    }
}
return source.indexOf(target);
posted @ 2019-04-02 21:40  故人叹  阅读(143)  评论(0)    收藏  举报