【问题标题】:Recursive vowel counter递归元音计数器
【发布时间】:2013-10-15 23:32:36
【问题描述】:

所以我被要求在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));
    }
}

【问题讨论】:

  • 问题是什么?
  • 我应该数一下元音的个数。我的教授建议我将字符串“ieoua”与使用元音方法调用的字符串进行比较并尝试获取计数……但是,我不知道这怎么可能?
  • 嘿,我没有看到字符“?” (问题);D
  • 但是'?'是 char 来创建问题....好吧,我确实测试了更快的方法:递归或非递归(使用 for 循环)

标签: java recursion


【解决方案1】:

您可以将 s.charAt(0) == 'a' || s.charAt(0) == 'i' || ... 更改为 "iouea".contains(Character.toString(s.charAt(0))) - 这似乎是您问题的答案。
但是因为您应该假设输入字符串 s 还包含大写元音 ('A'),所以您应该在方法开头使用 s = s.toLowerCase()s 设为小写。这样您的代码就会变得更简单。
UPD:有一个错误。将代码更改为Character.toString

【讨论】:

  • 我正要使用 Pattern 和 Matcher 写出答案,但您的解决方案要优雅得多。漂亮!
  • @P.성미 contains 检查传入的字符串是否包含在“iouea”中。例如:"iouea".contains("e"); 为真。但“c”不是这样
  • "iouea".contains(new String(s.charAt(0)) charAt(0) 会产生错误,因为它是一个字符,我们使用的是字符串?
  • "iouea".contains 接受 CharSequence 参数。 StringCharSequences.charAt(0) 返回char。为了使"iouea".contains 调用成为可能,我们将char 包裹在String 中,所以我们使用new String(s.charAt(0))。试试看。
  • 我确实做到了,它只有在我输入以下内容时才有效:"ioeua".contains(new String(s.substring(1)))
【解决方案2】:

在字符串上调用 indexOf 可以判断传入的字符是否在该字符串中:

if ("aeiou".indexOf(Character.toLowerCase(s.charAt(0))) != -1) {
    // first char of s is a vowel
}

【讨论】:

    【解决方案3】:

    你的意思是:

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

    ???我英语说得不太好,我用谷歌翻译

    编辑:第二种和更短的方法:

    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
    

    下一个编辑:我测试了速度计数字符:

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

    【讨论】:

    • 他的问题专门要求递归解决方案,而不是循环
    • 那是使用一个基本上很简单的开关......但我被要求使用递归来解决它。
    • 他的问题是如何写一个递归元音计数器
    • @StormeHawke 我只想指出循环是递归的一种形式。
    • 另外要指出的是,最好去掉除最后一个 vowels++;break; 之外的所有语句
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 2012-10-04
    • 2019-09-01
    • 2016-02-19
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多