“凯易迅Calix”实习上机——求元音开头辅音结尾的子串

时间:2023-03-10 02:36:00
“凯易迅Calix”实习上机——求元音开头辅音结尾的子串

题目要求:

  对于一个输入的字符串(26个小写字母组成),求出他的所有子串中元音开头,辅音结尾的子串。在这所有的子串中,输出第一个和最后一个。

  例如aab,共有子串a,aa,aab,ab,b;但是满足元音开头,辅音结尾的子串有aab,ab.

  预备知识:元音字母:a,o,e,i,u,其他均为辅音字母。

解题思路:

  1、首先创建一个元音字母集合yuanChars;一个辅音字母集合fuChars;

  2、For 遍历这个字符串,

      当前字母是辅音时,continue;//子串要求必须元音开头

      当前字母是元音是,then

        for 遍历后面的字符串;

          if 字母是元音,continue;//子串结尾字母必须辅音

          else 将子串添加到结果集合中

          end if

        end for

    end For

 这个算法只能测试通过部分示例,也就是说算法是可以优化的;时间复杂度可以降低,目前暂没考虑怎么降低,代码如下:

import java.util.HashMap;
import java.util.TreeSet; public class StringSequence {
public static void main(String[] args) {
String string="aab";//output:aab,ab
TreeSet<Character> allChars=new TreeSet<>();
for (int i = 97; i < 123; i++) {
allChars.add((char)i);
}
//System.out.println(allChars); TreeSet<Character> fuChars=allChars;
fuChars.remove('a');
fuChars.remove('o');
fuChars.remove('e');
fuChars.remove('i');
fuChars.remove('u');
//System.out.println(fuChars); TreeSet<Character> yuanChars=new TreeSet<>();
yuanChars.add('a');
yuanChars.add('o');
yuanChars.add('e');
yuanChars.add('i');
yuanChars.add('u');
//System.out.println(yuanChars);
// 截止目前,fuChars存放輔音字符;yuanChars存放元音字母 HashMap<Integer, String> result=new HashMap<>(); for (int i = 0; i < string.length(); i++) {
char temp=string.charAt(i); //如果不以元音字母開頭,直接退出
if(!yuanChars.contains(temp)){
continue;
} //辅音字母开头
for (int j = i+1; j < string.length(); j++) {
char point=string.charAt(j);
if (!fuChars.contains(point)) {
continue;
}
else {
String subStr=string.substring(i, j+1);//因为包括i;不包括j+1 result.put(result.size(), subStr);
//System.out.println(subStr);
}
}
} if (result.size()!=0) {
System.out.println(result.get(0));
System.out.println(result.get(result.size()-1));
} }
}