java经典算法-字符串(一)

对于一个给定的源字符串和一个目标字符串,你应该输出目标字符串的第一个索引(从0)在源字符串。

如果在源目标不存在,就返回1。

例子

If source = “source” and target = “target”, return -1.

If source = “abcdabcdefg” and target = “bcd”, return 1.

代码实现:

     

package com.asiainfo;

public class StrTest1 {

	
	public static int caculateStr(String source,String target){
		
		if(source == null && target == null){
		
			return 0;
		
		}
		if(source == null){
			 
			return -1;
		
		}
		if(target == null){
			
			return 0;
		}
		if(source.length() < target.length()){
			
			return -1;
			
		}
		for(int i = 0; i < source.length() - target.length() + 1 ; i ++){
			
			int j = 0;
			
			for(;j < target.length(); j ++){
				
				if(source.charAt(i + j) != target.charAt(j)){
					
					break;
					
				}
			}
			if(j == target.length()){
				
				return i;
				
			}
		}
		return -1;
	}
	
    public static void main(String[] args) {
       
    	String source = "abcdefg";
		
		String target = "cd";
		
		int result = caculateStr(source,target);
		
		System.out.print(result); //2
		
		
		 target = "cdx";
		
		 result = caculateStr(source,target);
		
		System.out.print(result); //-1
		
		 target = "cdxxxxxxxxxxxxxxxxx";
			
		 result = caculateStr(source,target);
		
		System.out.print(result); //-1
	
	}
	
}

写的不好,希望大家多提意见!

点赞