您的位置:首页 > 编程语言 > Java开发

Java编程:合并字符串并排序:判断丑陋数:找到最多含有n个不同字符的子串的最长长度

2016-12-14 13:26 375 查看
[java] view
plain copy

 





package com.baiyi;  

import java.util.*;  

public class TestUtils   

{  

      

    /** 

     * 第一题:合并字符串并排序 

     * 

     * @param str1 字符串 

     * @param str2 字符串 

     * @return 字符串 

     */  

    public static String comSort(String str1, String str2) throws Exception   

    {  

        // 请在此添加代码  

        int[] a=new int[26];  

        for(int i=0;i<26;i++)  

        {  

            a[i]=0;  

        }  

        for(int i=0;i<str1.length();i++)  

        {  

            a[str1.charAt(i)-'a']=1;  

        }  

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

        {  

            a[str2.charAt(i)-'a']=1;  

        }  

        String str="";  

        int sum=0;  

        for(int i=0;i<26;i++)  

        {  

            if(a[i]!=0)  

                sum++;  

        }  

        char[] b=new char[sum];  

        int j=0;  

        char i=0;  

        for(;i<26;i++)  

        {  

            if(a[i]!=0)  

            {  

                b[j]=(char) ('a'+i);  

                j++;  

            }  

        }  

        str =String.valueOf(b);  

        return str;  

    }  

      

    /* 

    第二题:找到最多含有n个不同字符的子串的最长长度 

    */  

    public static int change(String s,int n)  

    {  

        LinkedList<Character> list = new LinkedList<Character>();  

        int sum=1,max=0;  

        list.add(s.charAt(0));  

        for(int i=1;i<s.length();i++)  

        {  

            System.out.println(list.toString());  

            if(list.contains(s.charAt(i)))  

            {  

                list.add(s.charAt(i));  

            }  

            else  

            {  

                if(sum==n)  

                {  

                    if(list.size()>max)  

                        max=list.size();  

                    list.removeFirst();  

                    list.add(s.charAt(i));  

                      

                }  

                else  

                {  

                    list.add(s.charAt(i));  

                    sum++;  

                }  

            }  

  

        }  

        return max;  

    }  

    /* 

    第三题:判断丑陋数,质因数只有2,3,5的数是丑陋数 

    */  

    public static boolean isUgly(int num)   

    {  

        if (num <= 0)  

            return 0;  

        while (num % 2 == 0)   

            num /= 2;  

        while (num % 3 == 0)  

            num /= 3;  

        while (num % 5 == 0)  

            num /= 5;  

        return num==1?1:0;  

    }     

}  

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐