日期:2014-05-20  浏览次数:20710 次

请高手来看看数组下标溢出
//找出两个字符串中所有相同的子串
import java.util.*;
public class 找出共同的子串 {
public static void FindSon(String str1,String str2)
{
String a[]=new String[(str1.length()+1)*str1.length()/2];
String b[]=new String[(str2.length()+1)*str2.length()/2]; //获得str1和str2的子串总数
int x=0,y=0;
for(int i=0;i<str1.length();i++)
{
for(int j=i+1;j<=str1.length();j++)
{
a[x]=str1.substring(i,j);
x++;
}
}

for(int i=0;i<str2.length();i++)
{
for(int j=i+1;j<=str2.length();j++)
{

b[y]=str2.substring(i,j);
y++;
}
}
for(int i=0;i<a.length;i++)
{
int k=0;
for(int j=0;j<b.length;j++)
{
if(a[i].equals(b[i]))
{
k++;
}
}
if(k>0) System.out.print(a[i]+" ");

}

}
public static void main(String args[]) {
// TODO Auto-generated method stub
System.out.println("输入两个字符串:");
Scanner sc=new Scanner(System.in);
String str1=sc.next();
String str2=sc.next();
FindSon(str1,str2);
}

}



a[x]=str1.substring(i,j);
为什么这里赋不了值?
没报错,运行后没反映

------解决方案--------------------
Java code

    for (int i = 0; i < a.length; i++) {
            int k = 0;
            for (int j = 0; j < b.length; j++) {
                if (a[i].equals(b[i])) {
                    k++;
                }
            }
            if (k > 0)
                System.out.print(a[i] + " ");
        }

------解决方案--------------------
你这段代码计算结果不明朗,给你优化一下
Java code

public class FindSon3 {
    public static void FindSon(String str1, String str2) {
        HashMap setStr1 = new HashMap();
        HashMap setStr2 = new HashMap();
        int x = 0, y = 0, p = 0, q = 0;
        
        for (int i = 0; i < str1.length(); i++) {
            for (int j = i + 1; j <= str1.length(); j++) {
                if (!setStr1.containsValue(str1.substring(i, j))) {
                    setStr1.put(p, str1.substring(i, j));
                    x++;
                    p++;
                }
            }
        }

        for (int i = 0; i < str2.length(); i++) {
            for (int j = i + 1; j <= str2.length(); j++) {
                if (!setStr2.containsValue(str2.substring(i, j))) {
                    setStr2.put(q, str2.substring(i, j));
                    y++;
                    q++;
                }
            }
        }

        System.out.println();
        for (int i = 0; i < setStr1.size(); i++) {
            int k = 0;
            for (int j = 0; j < setStr2.size(); j++) {
                if (setStr1.get(i).equals(setStr2.get(j))) {
                    k++;
                }
            }
            if (k > 0)
                System.out.print(setStr1.get(i) + " ");
        }

    }

    public static void main(String args[]) {
        // TODO Auto-generated method stub
        System.out.println("输入两个字符串:");
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        String str2 = sc.next();
        FindSon(str1, str2);
    }

}