C++ language algorithm to find the maximum distance between any two identical characters

ask questions

We have a string like abcaffdffqwwwwwwrcs, what is the maximum length? We found that the direct distance between two cs is the largest, and the maximum length here should be the position of the second c - the position of the first c.

Algorithm ideas

Let's talk about the algorithm is the realization idea:
first, let's see, how do we find the distance between the first letter a, we first determine that the position of a is the first, we use a variable to save the position of a, and then pass To move the subscript to the position of 2 a's at the end, you only need to subtract the first position from the second position, which gives the distance between the two letters.
So the question is, we have so many characters in a string, so how do we store the position of each character. Here, you only need to record the position of each character in an array, use the ascii code of the character as the subscript of the array, and then access it through this subscript to directly record or read the position of the array record.
At this time, we can record the position of each character, but at this time, how to find the direct distance between any two characters, we need a variable to record the maximum distance, and compare the distance between any two characters with this variable, if If it is farther, it is recorded in this variable, and the entire string is read again.

Algorithm implementation

//C++实现方法
public:
    static int lengthOfLongestSubstring(String s){
        vector<int> dict(256,-1);
        int maxLen = 0,start = -1;
        for(int i = 0;i<s.length();i++){
            if(dict[s[i]] > -1){
                start = dict[s[i]];
                maxLen  = max(maxLen,i-start)'
            }
            dict[s[i]] = i;
        }
        return max;
    }
//C语言实现方法
int lengthOfLongestSubstring(const char * str) {
    int dict[256];
    int i = 0;
    for (; i<256; i++) {
        dict[i] = -1;
    }
    int maxLen = 0;
    for (i = 0; i < strlen(str); i++) {
        if (dict[str[i]]>-1) {
            maxLen = max(maxLen, i - dict[str[i]]);
        }
        dict[str[i]] = i;
    }
    return maxLen;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325464271&siteId=291194637