1. 程式人生 > 其它 >21.1.25 LeetCode Longest Substring Without Repeating Characters

21.1.25 LeetCode Longest Substring Without Repeating Characters

技術標籤:寒假學習

Longest Substring Without Repeating Characters

題意

給定一個字串s,求最長子字串的長度(不含重複字元)。

思路

1.對於長度i的字串,比對是否有滿足題意的答案
2.有則記錄i,並判斷i+1;
3,若對於所有長度為i的字串都不符合題意沒有則返回i-1

程式碼

#include <stdio.h>
bool check(int length, int start,char *s)
{
    for (int i = 0; i < length; i++)
    {
        for (int j =
0; j < i; j++) { if (s[i + start] == s[j + start]) return false; } } return true; } int lengthOfLongestSubstring(char* s) { int strsize=0; for (int i = 0; s[i] != '\0'; i++) { strsize++; } int num = 0; int flag = 0
;//1存在重複 0無重複 for (int i = 0; i <strsize; i++)//字串長度 { for (int j = 0; j < strsize - i; j++)//long i string kinds { if (check(i + 1, j, s)) { num++; break; } if (j == strsize - i - 1) return
num; } } return num; } int main() { char str[] = "abcabcbb"; printf("%d",lengthOfLongestSubstring(str)); return 0; }```