加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

字符串最大子串求法

(2013-11-05 16:14:09)
标签:

search

it

算法

分类: 技术
给你一个字符串。求它最大子串。满足以下条件 包含的不重复元素不超过三个

public class MaxSubStr {

    static String sample1 = "aabcccaddddaadd";
    static String sample2 = "aabcccadddd";

    static String maxSubStr(String str) {
        char[] chs = new char[str.length()];
        str.getChars(0, str.length(), chs, 0);

        int maxLen = 0;
        String maxSubStr = null;
        for (int i = 0; i < str.length(); i++) {
            StringBuilder sb = new StringBuilder();
            int j = i;
            int maxCharNum = 0;

            for (; j < str.length(); j++) {
                if (maxCharNum < 3) {
                    if (sb.indexOf(String.valueOf(chs[j])) < 0) {
                        maxCharNum++;
                    }
                    sb.append(chs[j]);
                } else if (maxCharNum == 3) {
                    if (sb.indexOf(String.valueOf(chs[j])) < 0) {
                        break;
                    } else {
                        sb.append(chs[j]);
                    }
                } else {
                    break;
                }
            }

            String temp = sb.toString();
            if (temp.length() > maxLen) {
                maxLen = temp.length();
                maxSubStr = temp;
            }
        }

        return maxSubStr;
    }

    public static void main(String... args) {
        System.out.println(maxSubStr(sample1));
    }
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有