String leetcode 1624 The longest substring between two identical characters

Subject content

Here is a string s. Please return the length of the longest substring between two identical characters. These two characters are not included when calculating the length. If there is no such substring, return -1.

A substring is a continuous sequence of characters in a string.

Example 1:

Input: s = "aa"
Output: 0
Explanation: The optimal substring is the empty substring between two'a's.

Example 2:

Input: s = "abca"
Output: 2
Explanation: The optimal substring is "bc".

Example 3:

Input: s = "cbzxy"
Output: -1
Explanation: There is no character that appears twice in s, so -1 is returned.

Example 4:

Input: s = "cabbac"
Output: 4
Explanation: The optimal substring is "abba", and other non-optimal solutions include "bb" and "".

prompt:

1 <= s.length <= 300
s 只含小写英文字母

Source: LeetCode
Link: https://leetcode-cn.com/problems/largest-substring-between-two-equal-characters

c language answer

int maxLengthBetweenEqualCharacters(char * s){
    
    
    int len=strlen(s);
    int max=0;
    int i;
    char a[strlen(s)];
    for(i=0;i<len;i++){
    
    
        a[i]=s[i];
        for(int j=0;j<i;j++){
    
    
            if(s[i]==a[j]){
    
    
                if((i-j)>max)
                    max=i-j;
                break;
            }
        } 
    }
    return max-1;
}

to sum up:

Variables cannot be used to define an array. For example, char a[len] will report an error. The good habit of initializing the definition must be developed.

Wrong code, just because count=0 is not initialized

int maxLengthBetweenEqualCharacters(char * s){
    
    
    int len=strlen(s);
    int max=0;
    int i;
    // count用来判断是否有相等的两个字符,有了count就是1,没了就是0
    int count;
    char a[strlen(s)];
    for(i=0;i<len;i++){
    
    
        a[i]=s[i];
        for(int j=0;j<i;j++){
    
    
            if(s[i]==a[j]){
    
    
                count=1;
                if((i-j)>max)
                    max=i-j-1;
                break;
            }
        } 
    }
    if(count==1)
        return max;
    return -1;
}

Guess you like

Origin blog.csdn.net/mogbox/article/details/113046552