现在要用Java实现求两字符串的公串,如"sdfsdg123jhg","yuop123z",则应该返回"123".
如abcd1243 和 azzz12 的公串是a和12.求助高手!!!!

解决方案 »

  1.   

    import java.util.*;
    public class Match {
        private String source1;
        private String source2;
        private ArrayList<String>matcher;
        
        public Match(String source1,String source2){
            this.source1 = source1;
            this.source2 = source2;
            matcher = new ArrayList<String>();
        }
        
        public void match(){
            String longer;
            String shorter;
            if(source1.length()>=source2.length()){
                longer = source1;
                shorter = source2;
            }
            else{
                longer = source2;
                shorter = source1;
            }
            
            for(int i=shorter.length(); i>0; i--){
                for(int j=0; j+i<=shorter.length(); j++){
                    String tmp = shorter.substring(j,j+i);
                    if(longer.indexOf(tmp)>=0){
                        matcher.add(tmp);
                        shorter = shorter.replace(tmp,"");
                        break;
                    }
                }
            }
        }
        
        public void print(){
            System.out.println("matcher: "+matcher);
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Match m = new Match("abcd1243","azzz12");
            m.match();
            m.print();
            
            m = new Match("sdfsdg123jhg","yuop123z");
            m.match();
            m.print();
        }}
      

  2.   

    上面程序中,应该把
     shorter = shorter.replace(tmp,"");
    改成
     shorter = shorter.replaceAll(tmp,"");因为replace只能替换字符,而replace可以替换字符串.改动后运行无误,,
      

  3.   

    shorter = shorter.replace(tmp,"");
    改成
     shorter = shorter.replaceAll(tmp,"");因为replace只能替换字符,而replace可以替换字符串.改动后运行无误,,
    --------------------------
    看jdk1.5的javadoc,你就知道不改也可以
      

  4.   

    private ArrayList<String>matcher;中那个<String>是什么啊