int lengthOfLongestSubstring(char * s)
{
/* Longest string length */
int liLgstLen = 0;
/* On process string information */
int liPrgrLen = 0;
int liPrgrStrtIdx = 0;
int liPrgrEndIdx = 0;
/* iterate. Length of string will be under 50000 */
for(int i=0; i< 50000; i++)
{
/* facing null */
if( *(s+i) == 0x00 )
{
return liLgstLen;
}
/* first loop, not null, set 1 */
if( i == 0 )
{
liPrgrLen = 1;
liPrgrStrtIdx = 0;
liPrgrEndIdx = 0;
liLgstLen = liPrgrLen;
continue;
}
/* search current(i) character in on process string */
int liPrgrCharMatchedIdx = -1;
for( int j=liPrgrEndIdx; j>=liPrgrStrtIdx; j-- )
{
if( *(s+j) == *(s+i) )
{
/* get last index of matched char in on process string */
liPrgrCharMatchedIdx = j;
break;
}
}
/* not found, add 1 to on process information */
if( liPrgrCharMatchedIdx == -1 )
{
liPrgrLen++;
liPrgrEndIdx++;
}
/* found, change on process information */
else
{
liPrgrLen = i - liPrgrCharMatchedIdx;
liPrgrStrtIdx = liPrgrCharMatchedIdx +1;
liPrgrEndIdx = i;
}
if( liPrgrLen > liLgstLen )
{
liLgstLen = liPrgrLen;
}
}
return liLgstLen;
}
입력된 값중, 중복된 문자를 포함하지 않는 가장 긴 문자열의 길이를 반환하는 함수
한칸씩 움직이면서 지나온 문자열에 동일한 문자가 포함되어있는지 확인하며 길이를 구한다.
깃허브 주소:
https://github.com/binary-river/algorithms/blob/Master/lengthOfLongestSubstring.c
GitHub - binary-river/algorithms: algorithms practices
algorithms practices. Contribute to binary-river/algorithms development by creating an account on GitHub.
github.com
'CS > Algorithm' 카테고리의 다른 글
[C] 두 개의 수 더하기 (linked list) (0) | 2021.10.30 |
---|---|
[C] 나비배열 찾기 (Palindrome) (0) | 2021.10.30 |
[C] 중간값 구하기 (0) | 2021.10.30 |
[C] 숫자 거꾸로 만들기 (0) | 2021.10.30 |
[C] 더해서 특정값이 되는 수 찾기 (0) | 2021.10.30 |