2016-03-02 5 views
1

Я пытаюсь написать такой алгоритм в Java. Я тестирую ввод строки «abaab». Можно с уверенностью предположить, что строковые входы будут иметь строчные значения.Алгоритм, который выплескивает самую маленькую и самую большую подстроку, начиная с гласного и заканчивая согласным для String

Я затрудняюсь в проверке, где мой алгоритм будет неправильным (он выводит только «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)); 
    } 
+0

Возможно, вам лучше выбрать все строки, поместить их в список, а затем выяснить наименьший и самый большой. Ваша проблема в том, что после того, как вы найдете строку «ab», вы продолжаете и сбрасываете свои индексы. – Mike

ответ

2

Вот мой Решение: самая длинная подстрока всегда начинается с первого гласного и заканчивается последним согласным. Для кратчайшего, каждый раз, когда я читаю согласный, я смотрю на расстояние до предыдущего гласного и вижу, лучше ли это. Вы можете ' t ничего не делать, пока вы не прочитаете хотя бы один гласный.

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 longStartIndex=0; 
    int shortStartIndex=0; 
    int shortEndIndex=0; 
    int longEndIndex=0; 
    boolean findVowel = false; 
    int bestStart = 0; 
    int bestEnd = 0; 
    int shortest =Integer.MAX_VALUE; 

    for (int i = 0; i < charArray.length; i++) { 
     for (int z = 0; z < vowels.length; z++) { 
      if (charArray[i] == vowels[z]) { 
       if (!findVowel){ 
        // if this is the first vowel we see 
        longStartIndex = i; 
        shortStartIndex=i; 
        findVowel = true; 
       } 
       else { 
        shortStartIndex = i; 
       } 
      } 
     } 
     for (int j = 0; j < cons.length; j++) { 
      if (charArray[i] == cons[j]) { 
       if (findVowel){ 
        // if we have seen any vowel, this consonant is useless 
        longEndIndex = i; // this one is always than the previous for the largest 
        shortEndIndex = i; // we have to check if this one is better or not 
        if (shortEndIndex-shortStartIndex<shortest){ 
         bestStart = shortStartIndex; 
         bestEnd = shortEndIndex; 
         shortest = shortEndIndex-shortStartIndex; 
        } 
       } 
      } 
     } 
    } 
    System.out.println(input.substring(bestStart, bestEnd+1)); 
    System.out.println(input.substring(longStartIndex, longEndIndex+1)); 
} 
-1

Я чувствую, что ваша реализация слишком сложна. Есть несколько вещей, которые вы пытаетесь поймать:

1) Наименьшая подстрока от гласного до согласного: это будет либо длина 2 символа, либо 0 символов.

2) Самая длинная подстрока от гласного к согласным: Это будет расстояние от первой гласной до последнего согласного, при условии, что гласный стоит перед согласной - в противном случае длиной 0.

Ниже приведен пример реализации без проверки ошибки подстроки:

import java.util.*; 

public class cons { 
    public static void main(String...args) 
    { 
     String str = "abaab"; 

     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' }; 

     int firstVowel = -1,lastConsonant = -1; 
     int consVowel = -1; 
     ArrayList<Character> vowel, con; 

     //I use lists for the .contains() method. 

     con = new ArrayList<Character>(); 
     vowel = new ArrayList<Character>(); 

     for (Character c : vowels) 
      vowel.add(c); 
     for (Character c : cons) 
      con.add(c); 

     //Algorithm starts here 
     for(int i = 0; i < str.length() - 1; i++) 
     { 
      //position i is a vowel 
      if (vowel.contains(str.charAt(i))) 
      { 
       //if first vowel isn't set, set it 
       if (firstVowel == -1) 
        firstVowel = i; 
       if (!vowel.contains(str.charAt(i+1))) 
       { 
        consVowel = i; 
        lastConsonant = i+1; 
       } 
      } else { //Otherwise it's a consonant. 
       lastConsonant = i; //set last consonant 
      } 
     } 

     System.out.println(str.substring(firstVowel,lastConsonant)); 
     System.out.println(str.substring(consVowel, consVowel+2)); 
    } 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^