Home > OS >  Is this syntax array inside array?
Is this syntax array inside array?

Time:12-29

Below code snippet from Leetcode. the given exercise is to find the longest substring without repeating characters. I am trying to understand the logic from someone has posted the solution

I have below question is

  1. I have cnt and s are array. is this array inside array cnt[s[j]] and cnt[s[j]] ? how it works, please help to explain. I have tried to visualize the code execution using this

I have tried to understand below line . I tried to visualize the code execution using this site

#include <stdio.h>

int lengthOfLongestSubstring(char * s)
{
    if (s[0] == '\0')
        return 0;
    if (s[1] == '\0')
        return 1;
    
    int i,  j, len, max = 0;
    int cnt[255] = {0}; // array of counter
    //memset(cnt,0,sizeof(cnt));
    for (i=0; s[i]!=0; i  )
    {
        len = 0;
        for (j=i; s[j]!=0; j  )
        {  
            if (cnt[s[j]] == 0)          /* What does this mean since cnt and s both are array? is this called array inside array ? */
            {
                printf("iteration %d  %c\n",j,s[j]);
                cnt[s[j]]  ;
                len  ;
            }
            else
            { /* if character are not equal */
                break;
            }
        }
        if (len > max)
            max = len;
    }
    return max;
}

int main()
{
    char string1[] = "abcabcbb";
    printf("%d",lengthOfLongestSubstring(string1));
    return 0;
}

CodePudding user response:

The syntax a[b[i]] means the value in b[i] references the index from a to read.

So if you have int a[] = { 10, 100, 1000, 10000, 100000}; int b[] = { 3, 2, 1, 0}; then a[b[0]] resolves to a[3] which has the value 10000.

Note that this requires b to only have values that are valid indexes into a.

CodePudding user response:

It's not an array inside an array, it's using one array to get the subscript into another array.

When you see a complex expression you don't understand, split it up into simpler expressions.

cnt[s[j]]  ;

is roughly equivalent to

int charcode = s[j];
cnt[charcode]  ;

s is a string, so s[j] contains a character code. So this increments the element of cnt corresponding to that character code, and the final result is frequency counts of each character.

  •  Tags:  
  • c
  • Related