strStr

11/30/2017 update
这道题看似简单,但是能写出bug free还有有难度的。
My implementation:

-------------------------
 class Solution {  
   public int strStr(String haystack, String needle) {  
     if (needle.isEmpty()) return 0;  
     for (int i = 0; i <= haystack.length() - needle.length(); i++) {  
       if (haystack.charAt(i) == needle.charAt(0)) {  
         int temp = i;  
         int j = 1;  
         for (j = 1; j < needle.length(); j++) {  
           if (haystack.charAt(++temp) != needle.charAt(j)) {  
             break;  
           }  
         }  
         if (j == needle.length() ) return i;  
       }  
     }  
     return -1;  
   }  
 }  

Leetcode clean code hand book has a very genius implementation, I won't be able to reach that level. So skip it.

思路:
太简单了没啥好说的。
实现:
corner case不太容易想到,如果对string不熟的话。比如s=“ewffwe”, target=""。这个情况就要返回0。一开始检查corner case代码为:

if(source==null||target==null)  
       return -1;  
if(target.length()==0)  
       return 0;  

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array