用Java设计一个程序,实现一个字符串的对称个数,如字符串"effeghg",有"ff","effe","ghg"这三个对称字符,所以返回3.
我没写出来这个算法.请教高手!!!

解决方案 »

  1.   

    我刚刚写了一段代码给楼主参考下:
    /**
     * 
     */
    package com.lim.test.csdn;/**
     * @author bzwm
     * 
     */
    public class FindSymmetryStr {
    public static int findSymmetryStr(String orgStr) {
    int count = 0;
    if (orgStr != null && orgStr.length() > 1) {
    int size = orgStr.length(); int head; int current;
    char hStr;
    char cStr; for (head = 0; head < size; head++) {
    hStr = orgStr.charAt(head);
    current = size - 1;
    while (current > head) {
    cStr = orgStr.charAt(current); if (hStr == cStr) {
    String newStr = orgStr.substring(head + 1, current);
    if (newStr.length() > 1)
    count += findSymmetryStr(newStr);
    else if (newStr.length() == 1)
    count++;
    else {
    count++;
    }
    current--; } else {
    current--;
    }
    }
    }
    } return count;
    } public static void main(String args[]) {
    int count = findSymmetryStr("cddcbcbeffeghg");//
    System.out.println("symmetry string count is : " + count);
    }
    }
      

  2.   

    我把详细的内容写在这里了:
    http://blog.csdn.net/bzwm/archive/2008/12/22/3577023.aspx希望对你有帮助。
      

  3.   

    我接触的类比较少,或者有其他更直接有效的类和方法可用,我可能绕了弯路,提供你参考参考
    public class Te
    {
        int sum;
        public void check(String s)
        {
            for(int i=0;i<s.length();i++)
            {
                char c=s.charAt(i);   //取出第一个字符c
                String s1=s.substring(i+1);  //剩余的字符组成新字符串s1
                for(int j=0;j<s1.length();j++) 
                {
                    if(c==s1.charAt(j))  //比较c与s1中哪个字符相等
                    {
                        if(j==0||j==1)  //如果j=0或1,说明相等的两个字符相距0或1(像 ss 和 sws ),此时对称
                          sum++;
                        else{             //如果j等于其他,好像swkes,此时就取出wke,重复上述步骤
                            String s2=s1.substring(0,j);
                            check(s2);
                        }
                    }             
                                                   
                }
                
            }
        }
        public static void main(String []args)
        {
            Te t=new Te();
            t.check("effeghg");
            System.out.println(t.sum);
        }
    }