2013-10-15 5 views
0

Итак, меня попросили написать рекурсивный счетчик гласных в java, я в основном написал 2 очень похожих кода, но я хочу знать, как мне нравится подсчитывать гласные, если я сравниваю строку со строкой, состоящей из гласные?Рекурсивный счетчик гласных

Мои 2 коды:

public static int vowels(String s) { 

    if (s.length() == 0 || s == null) { 
     return 0; 
    } else if (s.charAt(0) == 'a' || s.charAt(0) == 'i' || s.charAt(0) == 'e' || s.charAt(0) == 'o' || s.charAt(0) == 'u') { 
     return 1 + vowels(s.substring(1)); 
    } else { 
     return vowels(s.substring(1)); 
    } 
} 

Второй: что является больше, но в основном такие же, как и предыдущий один

public static int vowels(String s) { 

     if(s.length() ==0){ 
     return 0; 
     } 
    } else if (s.charAt(0) == 'i') { 
     return 1 + vowels(s.substring(1)); 
    } else if (s.charAt(0) == 'o') { 
     return 1 + vowels(s.substring(1)); 
    } else if (s.charAt(0) == 'u') { 
     return 1 + vowels(s.substring(1)); 
    } else if (s.charAt(0) == 'e') { 
     return 1 + vowels(s.substring(1)); 
    } else if (s.charAt(0) == 'a') { 
     return 1 + vowels(s.substring(1)); 
    } else { 
     return 0 + vowels(s.substring(1)); 
    } 
} 
+4

Какой вопрос? – Cruncher

+0

Я должен считать количество гласных. Мой профессор предложил мне сравнить строку «ieoua» со строкой, вызванной методом гласных, и попытаться получить счет ... однако, я не знаю, как это возможно? – Scarl

+0

Хе-хе, я не вижу знака? (вопрос); D – barwnikk

ответ

3

Вы можете изменить s.charAt(0) == 'a' || s.charAt(0) == 'i' || ... к "iouea".contains(Character.toString(s.charAt(0))) - это, кажется, ответ на ваш вопрос.
Но поскольку вы должны предположить, что строка ввода s содержит также прописные гласные ('A'), вы должны сделать s строчные буквы с s = s.toLowerCase() в начале метода. Таким образом, вы упростите свой код.
UPD: была ошибка. Измененный код Character.toString

+0

Я не понимаю – Scarl

+0

Я как раз собирался написать ответ с помощью Pattern and Matcher, но ваше решение гораздо более изящный. Красивый! – StormeHawke

+1

@P. 성미 'contains' проверяет, если строка, переданная в нее, содержится внутри« iouea ». например: '' iouea ".contains (" e ");' true. Но не верно для «c» – Cruncher

0

вы имели в виду:

public int countVowels(String s) { 
    int vowels = 0; 
    s=s.toLowerCase(); 
    for(char c : s.toCharArray()) { 
     switch(c) { 
     case 'a': vowels++; break; 
     case 'e': vowels++; break; 
     case 'o': vowels++; break; 
     case 'u': vowels++; break; 
     case 'i': vowels++; break; 
     case 'y': vowels++; break; 
     default: 
     } 
    } 
    return vowels; 
} 

??? Я не могу говорить очень хорошо на английском языке, я использовал Перевести Google

EDIT: метод Второй и короче:

public static int countVowels(String s) { 
    int vowels = 0; 
    s=s.toLowerCase(); 
    for(char c : s.toCharArray()) { 
     if("euioa".contains(c+""))vowels++; 
    } 
    return vowels; 
} 

Второе редактирование: Если строка имеет больше символов, чем около 10000, а с помощью рекурсивной, то есть исключение, например:

Exception in thread "main" java.lang.StackOverflowError 
at sun.nio.cs.SingleByte.withResult(Unknown Source) 
at sun.nio.cs.SingleByte.access$000(Unknown Source) 
at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source) 
at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source) 
at java.nio.charset.CharsetEncoder.encode(Unknown Source) 
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source) 
at sun.nio.cs.StreamEncoder.write(Unknown Source) 
at java.io.OutputStreamWriter.write(Unknown Source) 
at java.io.BufferedWriter.flushBuffer(Unknown Source) 
at java.io.PrintStream.write(Unknown Source) 
at java.io.PrintStream.print(Unknown Source) 
at java.io.PrintStream.println(Unknown Source) 
at Test2.main(Test2.java:24) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
at Test2.main(Test2.java:25) 
    ... very very long 

СЛЕДУЮЩИЙ EDIT: Я сделал тест скорости подсчета символов:

[Test #1] Result with recursive: 4.263765 ms 
[Test #1] Result without (using contains, faster method): 2.69513 ms 
[Test #1] Result without (using switch): 0.346898 ms 
[Test #1] Result without (using if): 0.423256 ms 
[Test #1] Result without (using indexOf): 0.644943 ms 

[Test #2] Result with recursive: 6.40468 ms 
[Test #2] Result without (using contains, faster method): 4.177144 ms 
[Test #2] Result without (using switch): 0.263149 ms 
[Test #2] Result without (using if): 0.281624 ms 
[Test #2] Result without (using indexOf): 0.453225 ms 

[Test #3] Result with recursive: 4.314261 ms 
[Test #3] Result without (using contains, faster method): 2.073998 ms 
[Test #3] Result without (using switch): 0.428183 ms 
[Test #3] Result without (using if): 0.36373 ms 
[Test #3] Result without (using indexOf): 0.392467 ms 

[Test #4] Result with recursive: 5.740032 ms 
[Test #4] Result without (using contains, faster method): 2.053882 ms 
[Test #4] Result without (using switch): 0.160107 ms 
[Test #4] Result without (using if): 0.171192 ms 
[Test #4] Result without (using indexOf): 0.230718 ms 

[Test #5] Result with recursive: 3.19105 ms 
[Test #5] Result without (using contains, faster method): 1.833838 ms 
[Test #5] Result without (using switch): 0.144096 ms 
[Test #5] Result without (using if): 0.16257 ms 
[Test #5] Result without (using indexOf): 0.210192 ms 

[Test #6] Result with recursive: 2.586339 ms 
[Test #6] Result without (using contains, faster method): 1.41715 ms 
[Test #6] Result without (using switch): 0.152718 ms 
[Test #6] Result without (using if): 0.161338 ms 
[Test #6] Result without (using indexOf): 0.220865 ms 

[Test #7] Result with recursive: 2.445117 ms 
[Test #7] Result without (using contains, faster method): 1.134295 ms 
[Test #7] Result without (using switch): 0.164212 ms 
[Test #7] Result without (using if): 0.083749 ms 
[Test #7] Result without (using indexOf): 0.133833 ms 

[Test #8] Result with recursive: 1.995997 ms 
[Test #8] Result without (using contains, faster method): 0.987325 ms 
[Test #8] Result without (using switch): 0.058295 ms 
[Test #8] Result without (using if): 0.084569 ms 
[Test #8] Result without (using indexOf): 0.130959 ms 

[Test #9] Result with recursive: 4.914866 ms 
[Test #9] Result without (using contains, faster method): 0.335403 ms 
[Test #9] Result without (using switch): 0.057063 ms 
[Test #9] Result without (using if): 0.085801 ms 
[Test #9] Result without (using indexOf): 0.142865 ms 

[Test #10] Result with recursive: 1.164673 ms 
[Test #10] Result without (using contains, faster method): 0.330477 ms 
[Test #10] Result without (using switch): 0.058295 ms 
[Test #10] Result without (using if): 0.180223 ms 
[Test #10] Result without (using indexOf): 0.129728 ms 

[Test #11] Result with recursive: 1.089547 ms 
[Test #11] Result without (using contains, faster method): 0.391646 ms 
[Test #11] Result without (using switch): 0.073074 ms 
[Test #11] Result without (using if): 0.307487 ms 
[Test #11] Result without (using indexOf): 0.123159 ms 

[Test #12] Result with recursive: 3.442706 ms 
[Test #12] Result without (using contains, faster method): 0.24755 ms 
[Test #12] Result without (using switch): 0.052548 ms 
[Test #12] Result without (using if): 0.204855 ms 
[Test #12] Result without (using indexOf): 0.123159 ms 

[Test #13] Result with recursive: 0.521373 ms 
[Test #13] Result without (using contains, faster method): 0.251655 ms 
[Test #13] Result without (using switch): 0.047211 ms 
[Test #13] Result without (using if): 0.073074 ms 
[Test #13] Result without (using indexOf): 0.115359 ms 

[Test #14] Result with recursive: 0.540258 ms 
[Test #14] Result without (using contains, faster method): 0.261508 ms 
[Test #14] Result without (using switch): 0.053779 ms 
[Test #14] Result without (using if): 0.0858 ms 
[Test #14] Result without (using indexOf): 0.083748 ms 

[Test #15] Result with recursive: 0.554626 ms 
[Test #15] Result without (using contains, faster method): 0.26315 ms 
[Test #15] Result without (using switch): 0.056653 ms 
[Test #15] Result without (using if): 0.078411 ms 
[Test #15] Result without (using indexOf): 0.079232 ms 

[Test #16] Result with recursive: 0.529994 ms 
[Test #16] Result without (using contains, faster method): 0.253298 ms 
[Test #16] Result without (using switch): 0.058706 ms 
[Test #16] Result without (using if): 0.086622 ms 
[Test #16] Result without (using indexOf): 0.087443 ms 

[Test #17] Result with recursive: 0.520552 ms 
[Test #17] Result without (using contains, faster method): 0.267255 ms 
[Test #17] Result without (using switch): 0.055832 ms 
[Test #17] Result without (using if): 0.086622 ms 
[Test #17] Result without (using indexOf): 0.084569 ms 

[Test #18] Result with recursive: 0.531636 ms 
[Test #18] Result without (using contains, faster method): 0.260687 ms 
[Test #18] Result without (using switch): 0.058706 ms 
[Test #18] Result without (using if): 0.082927 ms 
[Test #18] Result without (using indexOf): 0.088675 ms 

[Test #19] Result with recursive: 0.654385 ms 
[Test #19] Result without (using contains, faster method): 0.25494 ms 
[Test #19] Result without (using switch): 0.059117 ms 
[Test #19] Result without (using if): 0.090317 ms 
[Test #19] Result without (using indexOf): 0.084159 ms 

[Test #20] Result with recursive: 0.551342 ms 
[Test #20] Result without (using contains, faster method): 0.28655 ms 
[Test #20] Result without (using switch): 0.083748 ms 
[Test #20] Result without (using if): 0.111664 ms 
[Test #20] Result without (using indexOf): 0.081696 ms 

[Test #21] Result with recursive: 1.042336 ms 
[Test #21] Result without (using contains, faster method): 1.165084 ms 
[Test #21] Result without (using switch): 0.068969 ms 
[Test #21] Result without (using if): 0.095653 ms 
[Test #21] Result without (using indexOf): 0.089496 ms 

[Test #22] Result with recursive: 0.555447 ms 
[Test #22] Result without (using contains, faster method): 0.27054 ms 
[Test #22] Result without (using switch): 0.066095 ms 
[Test #22] Result without (using if): 0.091137 ms 
[Test #22] Result without (using indexOf): 0.329656 ms 

[Test #23] Result with recursive: 2.345769 ms 
[Test #23] Result without (using contains, faster method): 0.109611 ms 
[Test #23] Result without (using switch): 0.082106 ms 
[Test #23] Result without (using if): 0.09278 ms 
[Test #23] Result without (using indexOf): 0.094833 ms 

[Test #24] Result with recursive: 0.565711 ms 
[Test #24] Result without (using contains, faster method): 0.079643 ms 
[Test #24] Result without (using switch): 0.089906 ms 
[Test #24] Result without (using if): 0.082517 ms 
[Test #24] Result without (using indexOf): 0.088264 ms 

[Test #25] Result with recursive: 0.552573 ms 
[Test #25] Result without (using contains, faster method): 0.078001 ms 
[Test #25] Result without (using switch): 0.052137 ms 
[Test #25] Result without (using if): 0.095654 ms 
[Test #25] Result without (using indexOf): 0.089085 ms 

Код испытания:

static int i = 0; 
private static long start; 
private static long end; 
public static void main(String[] args) { 
    for(int j=0; j<25; j++) { 
     test(); 
    } 
} 
public static void test() { 
    i++; 
    String string = "aurwgn iowthpbomaj yo4jpb 4y9 b0q thaioe vau hewoimjnyoj ioajr " 
      + "itwejb iwojaoehmtuwehtoawegtoam yierjspyomrahvuir auyheroiamvyirhapivthe " 
      + "awibthnapeutmbhuewath huaheovgayeutn jeryhaipmvhtuwea htpaw thwuaurwgn iowthpbomaj yo4jpb 4y9 b0q thaioe vau hewoimjnyoj ioajr " 
      + "itwejb iwojaoehmtuwehtoawegtoam yierjspyomrahvuir auyheroiamvyirhapivthe " 
      + "awibthnapeutmbhuewath huaheovgayeutn jeryhaipmvhtuwea htpaw thwuaurwgn iowthpbomaj yo4jpb 4y9 b0q thaioe vau hewoimjnyoj ioajr " 
      + "itwejb iwojaoehmtuwehtoawegtoam yierjspyomrahvuir auyheroiamvyirhapivthe " 
      + "awibthnapeutmbhuewath huaheovgayeutn jeryhaipmvhtuwea htpaw thwuaurwgn iowthpbomaj yo4jpb 4y9 b0q thaioe vau hewoimjnyoj ioajr " 
      + "itwejb iwojaoehmtuwehtoawegtoam yierjspyomrahvuir auyheroiamvyirhapivthe " 
      + "awibthnapeutmbhuewath huaheovgayeutn jeryhaipmvhtuwea htpaw thwuaurwgn iowthpbomaj yo4jpb 4y9 b0q thaioe vau hewoimjnyoj ioajr " 
      + "itwejb iwojaoehmtuwehtoawegtoam yierjspyomrahvuir auyheroiamvyirhapivthe " 
      + "awibthnapeutmbhuewath huaheovgayeutn jeryhaipmvhtuwea htpaw thwu"; 
    start = System.nanoTime(); 
    countVowels2(string); 
    end = System.nanoTime(); 
    System.out.println("[Test #"+i+"] Result with recursive: "+(end-start)/1000000.0+" ms"); 
    start = System.nanoTime(); 
    countVowels(string); 
    end = System.nanoTime(); 
    System.out.println("[Test #"+i+"] Result without (using contains, faster method): "+(end-start)/1000000.0+" ms"); 
    start = System.nanoTime(); 
    countVowels3(string); 
    end = System.nanoTime(); 
    System.out.println("[Test #"+i+"] Result without (using switch): "+(end-start)/1000000.0+" ms"); 
    start = System.nanoTime(); 
    countVowels4(string); 
    end = System.nanoTime(); 
    System.out.println("[Test #"+i+"] Result without (using if): "+(end-start)/1000000.0+" ms"); 
    start = System.nanoTime(); 
    countVowels5(string); 
    end = System.nanoTime(); 
    System.out.println("[Test #"+i+"] Result without (using indexOf): "+(end-start)/1000000.0+" ms"); 
    System.out.println(); 
} 
public static int countVowels(String s) { 
    int vowels = 0; 
    s=s.toLowerCase(); 
    for(char c : s.toCharArray()) { 
     if("euioa".contains(c+""))vowels++; 
    } 
    return vowels; 
} 
public static int countVowels2(String s) { 
    if(s.length()==0)return 0; 
    if("euioa".contains(s.charAt(0)+""))return 1+countVowels2(s.substring(1)); 
    return countVowels2(s.substring(1)); 
} 
public static int countVowels3(String s) { 
    int vowels = 0; 
    s=s.toLowerCase(); 
    for(char c : s.toCharArray()) { 
     switch(c) { 
     case 'a': vowels++; break; 
     case 'e': vowels++; break; 
     case 'o': vowels++; break; 
     case 'u': vowels++; break; 
     case 'i': vowels++; break; 
     case 'y': vowels++; break; 
     default: 
     } 
    } 
    return vowels; 
} 
public static int countVowels4(String s) { 
    int vowels = 0; 
    s=s.toLowerCase(); 
    for(char c : s.toCharArray()) { 
     if(c=='a'||c=='e'||c=='o'||c=='u'||c=='i'||c=='y')vowels++; 
    } 
    return vowels; 
} 
public static int countVowels5(String s) { 
    int vowels = 0; 
    s=s.toLowerCase(); 
    for(char c : s.toCharArray()) { 
     if("euioa".indexOf(c)!=-1)vowels++; 
    } 
    return vowels; 
} 
+0

Его вопрос специально спросил о рекурсивном решении, а не о петле – StormeHawke

+0

Итак, в чем вопрос? Сколько гласных в String? – barwnikk

+0

Это с помощью переключателя, который в основном довольно простой. Но меня попросят разобраться с рекурсией. – Scarl

2

Вызов IndexOf на строку говорит, если символ передается в в этой строке:

if ("aeiou".indexOf(Character.toLowerCase(s.charAt(0))) != -1) { 
    // first char of s is a vowel 
} 
Смежные вопросы