从给定的字符串数组和字符串模式中找到最大的单词

问题描述 投票:-2回答:1

从给定的字符串数组和字母字符串模式中找到最大的单词,该单词可以包含重复/重复的字符/字母,但是在计算单词的长度时,必须忽略重复的字母,仅计数唯一字符。第二个字母模式参数包含一些字母,例如“ ABCDEF”,这是实现所需输出的另一条件,字符串数组中的单词在查找最大单词时应包含字母模式(“ ABCEDF”)。这里的顺序与模式无关。

java string unique word
1个回答
0
投票

查找最长子串的长度而不重复字符:

    static final int NO_OF_CHARS = 256; 

    static int longestUniqueSubsttr(String str) 
    { 
        int n = str.length(); 
        int cur_len = 1; // length of current substring 
        int max_len = 1; // result 
        int prev_index; // previous index 
        int i; 
        int visited[] = new int[NO_OF_CHARS]; 

        /* Initialize the visited array as -1, -1 is  
         used to indicate that character has not been  
         visited yet. */
        for (i = 0; i < NO_OF_CHARS; i++) { 
            visited[i] = -1; 
        } 

        /* Mark first character as visited by storing the 
             index of first   character in visited array. */
        visited[str.charAt(0)] = 0; 

        /* Start from the second character. First character is 
           already processed (cur_len and max_len are initialized 
         as 1, and visited[str[0]] is set */
        for (i = 1; i < n; i++) { 
            prev_index = visited[str.charAt(i)]; 

            /* If the current character is not present in 
           the already processed substring or it is not 
              part of the current NRCS, then do cur_len++ */
            if (prev_index == -1 || i - cur_len > prev_index) 
                cur_len++; 

            /* If the current character is present in currently 
               considered NRCS, then update NRCS to start from 
               the next character of the previous instance. */
            else { 
                /* Also, when we are changing the NRCS, we 
                   should also check whether length of the 
                   previous NRCS was greater than max_len or 
                   not.*/
                if (cur_len > max_len) 
                    max_len = cur_len; 

                cur_len = i - prev_index; 
            } 

            // update the index of current character 
            visited[str.charAt(i)] = i; 
        } 

        // Compare the length of last NRCS with max_len and 
        // update max_len if needed 
        if (cur_len > max_len) 
            max_len = cur_len; 

        return max_len; 
    } 

    /* Driver program to test above function */
    public static void main(String[] args) 
    { 
        String str = "ABDEFGABEF"; 
        System.out.println("The input string is " + str); 
        int len = longestUniqueSubsttr(str); 
        System.out.println("The length of "
                           + "the longest non repeating character is " + len); 
    } 

Reference

© www.soinside.com 2019 - 2024. All rights reserved.