我想用Java編寫這樣的算法。我正在測試字符串輸入「abaab」。假設字符串輸入爲小寫是安全的。算法,吐出最小和最大的子字符串,以元音開始,並以字母串輔音結尾
我在檢查在我的算法是怎麼了虧損(僅輸出「AA」此輸入,而不是「AB」和「abaab」。任何想法?
static void SmallestAndLargestSubstring(String input) {
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
char[] cons = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x',
'y', 'z' };
char[] charArray = input.toLowerCase().toCharArray();
int startIndex = 0;
int shortEndIndex = 0;
int longEndIndex = 0;
int large = longEndIndex - startIndex;
int small = shortEndIndex - startIndex;
ArrayList<Integer> start = new ArrayList<Integer>();
ArrayList<Integer> end = new ArrayList<Integer>();
outerloop: for (int i = 0; i < charArray.length; i++) {
for (int z = 0; z < vowels.length; z++) {
if (charArray[i] == vowels[z]) {
startIndex = i;
start.add(startIndex);
if (longEndIndex - startIndex > large) {
large = longEndIndex - startIndex;
}
if(longEndIndex - startIndex <= large){
shortEndIndex=start.get(start.size()-1);
}
if (shortEndIndex - startIndex < small) {
small = shortEndIndex - startIndex;
}
if(shortEndIndex - startIndex >=small){
shortEndIndex=start.get(start.size()-1);
}
continue outerloop;
}
}
for (int j = 0; j < cons.length; j++) {
if (charArray[i] == cons[j]) {
longEndIndex = i;
shortEndIndex = i;
end.add(longEndIndex);
if (longEndIndex - startIndex > large) {
large = longEndIndex - startIndex;
}if(longEndIndex - startIndex <= large){
longEndIndex=end.get(end.size()-1);
}
if (shortEndIndex - startIndex < small) {
small = shortEndIndex - startIndex;
}
if(shortEndIndex - startIndex >=small) {
shortEndIndex=end.get(end.size()-1);
}
continue outerloop;
}
}
}
System.out.println(input.substring(startIndex, shortEndIndex));
System.out.println(input.substring(startIndex, longEndIndex));
}
你可能會更好挑選出所有的字符串,把它們放入一個列表,然後找出最小和最大。你的問題是,你發現「ab」字符串後,你繼續並重置你的索引。 – Mike