编写一个接受 1 个参数的函数:一个字符串,s。它必须返回一个整数,表示 s? 中最长的神奇子序列的长度?

Techno_Stud

考虑一个字符串 s,它由以下一个或多个字母组成:a、e、i、o 和 u。

我们将 s 的神奇子序列定义为从 s 派生的字母序列,它按顺序包含所有五个元音。这意味着一个神奇的子序列将具有一个或多个 a 后跟一个或多个 e 后跟一个或多个 i 后跟一个或多个 o 后跟一个或多个 u。例如,如果 s = "aeeiooua",那么 "aeiou" 和 "aeeioou" 是神奇的子序列,但 "aeio" 和 "aeeioua" 不是。

编写一个函数,用参数字符串 s 找出最长神奇子序列的长度。

Input Format
String s composed of English vowels (i.e., a, e, i, o, and u).

Output Format
Count denoting the length of the longest magical subsequence in s.


    Sample Input 1
    aeiaaioooaauuaeiou



Sample Output 1
10

Explanation 1
In the table below, the component characters of the longest magical subsequence are red:
a   e   i   a   a   i   o   o   o   a   a   u   u   a   e   i   o   u

Sample Input 2
aeiaaioooaa

Sample Output 2
0

Explanation 2
String s does not contain the letter u, so it is not possible to construct a magical subsequence

I

所以这个问题的java代码是这样的。

import java.util.Arrays; import java.util.Scanner;
public class LongestMegicalSubsequence {
static int longestMegicalSubsequence(String s, char[] c) {

    // exit conditions
    if (s.length() == 0 || c.length == 0) {
        return 0;
    }

    if (s.length() < c.length) {
        return 0;
    }

    if (s.length() == c.length) {
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != c[i]) {
                return 0;
            }
        }
        return s.length();
    }

    if (s.charAt(0) < c[0]) {
        // ignore, go ahead with next item
        return longestMegicalSubsequence(s.substring(1), c);
    } else if (s.charAt(0) == c[0]) {

        return Math.max(Math.max(
                (1 + longestMegicalSubsequence(s.substring(1),
                        Arrays.copyOfRange(c, 1, c.length))),
                (1 + longestMegicalSubsequence(s.substring(1), c))),
                (longestMegicalSubsequence(s.substring(1), c)));
    } else {
        return longestMegicalSubsequence(s.substring(1), c);
    }
}

public static void main(String...s) {

    char[] chars = { 'a', 'e', 'i', 'o', 'u' };
    System.out.print("PLEASE ENTER THE STRING");
    Scanner sc =new Scanner(System.in);

    String str = sc.next();

    System.out.println(longestMegicalSubsequence(str, chars));


}
}

我只是想在 python 中解决这个问题。
但想不出一个pythonic的方式来做到这一点。我的意思是我转换了 python 代码中的每一行逻辑,但这不是我的动机。你能告诉我一种在 python 中做到这一点的方法吗?

BM

这是一个python版本。

def f(input):
    pattern='aeiou'
    total=0
    c=0
    for x in input:
        if x==pattern[c]:
            c+=1
            if c==5:
                total += 5
                c=0
    return total

文本 :

In [12]: f('aeiaaioooaauuaeiou')
10

或者,更多的算术:

def f(input):
    pattern='aeiou'
    c=0
    for x in input:
        c += (x==pattern[c%5])
    print(c//5*5)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章