waysun一路陽光

          不輕易服輸,不輕言放棄.--心是夢的舞臺,心有多大,舞臺有多大。踏踏實實做事,認認真真做人。

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 ::  :: 管理 ::
            167 隨筆 :: 1 文章 :: 64 評論 :: 0 Trackbacks
          轉自:http://www.aygfsteel.com/javacap/archive/2007/07/10/129405.html
          /**
           
          * Demonstrate KMP algorithm in Java
           
          *
           
          *
           
          */
          public class KMP {
              
              
              
          public static int indexOf(String target,String pattern)
              {
                  
          int pLen=pattern.length();
                  
          int tLen=target.length();
                  
                  
          //the fail function
                  int failFunc[]=new int[pLen];
                  
                  failFunc[
          0]=-1;
                  
                  
          //build fail function
                  for(int i=1;i<pLen;i++)
                  {
                      
          int j=failFunc[i-1];
                      
          while(pattern.charAt(i)!=pattern.charAt(j+1)&&j>=0)
                      {
                          
          //recursion 
                          j=failFunc[j];
                      }
                      
          if(pattern.charAt(i)==pattern.charAt(j+1))
                      {
                          failFunc[i]
          =j+1;
                      }
                      
          else 
                      {
                          failFunc[i]
          =-1;
                      }
                  }

                  
          int pPos=0,tPos=0;
                  
                  
          while(tPos<tLen&&pPos<pLen)
                  {
                      
          if(target.charAt(tPos)==pattern.charAt(pPos))
                      {
                          
          //match ,then do forward
                          tPos++;
                          pPos
          ++;
                      }
                      
          else if(pPos==0)
                      {
                          
          //target go forward
                          tPos++;
                      }
                      
          else
                      {
                          
          //target postion don't change,pattern go back  
                          pPos=failFunc[pPos-1]+1;
                      }
                  }
                  
                  
          if(pPos<pLen)return -1;
                  
          else return tPos-pLen;
                  
                  
                  
              }

          }

          posted on 2009-04-15 22:27 weesun一米陽光 閱讀(431) 評論(0)  編輯  收藏 所屬分類: JAVA源碼總結備用
          主站蜘蛛池模板: 于田县| 金堂县| 尼木县| 金湖县| 凭祥市| 南部县| 乌鲁木齐市| 广饶县| 邓州市| 靖江市| 原平市| 阿克苏市| 民县| 凤凰县| 逊克县| 大港区| 县级市| 会理县| 四平市| 丹寨县| 双江| 九江县| 道真| 左云县| 连云港市| 长泰县| 大足县| 织金县| 潼关县| 临邑县| 海南省| 望城县| 武穴市| 巫山县| 阳山县| 恩平市| 民权县| 南宁市| 新巴尔虎左旗| 肥西县| 城步|