- 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;
- }
- }
- }
Java编程:合并字符串并排序:判断丑陋数:找到最多含有n个不同字符的子串的最长长度
最新推荐文章于 2025-12-17 19:02:04 发布
本文介绍了几种实用的字符串处理算法,包括合并并排序两个字符串中的唯一字符、寻找包含特定数量不同字符的最长子串,以及判断一个数是否为丑陋数(质因数仅为2、3、5)。通过具体的Java代码示例,展示了这些算法的设计思路和实现细节。
1228

被折叠的 条评论
为什么被折叠?



