程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Longest Substring Without Repeating Characters(C語言實現),longestrepeating

Longest Substring Without Repeating Characters(C語言實現),longestrepeating

編輯:關於C語言

Longest Substring Without Repeating Characters(C語言實現),longestrepeating


Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

 題目地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/

題目意思:給出一個字符串,輸出最長的子串的長度,子串不能有重復的字符。(子串是連續的。)

解題思路:   依次讀取字符串的每一個字符,如果第一次出現則當前子串長度+1,否則:首先判斷當前長度是否大於最大長度,是則替換最大長度。然後

      查找重復的字符是在原字符串哪裡出現的。

代碼如下:

 1 int lengthOfLongestSubstring(char* s) {
 2     int maxlen = 0,currlen = 0;
 3     int table[128], i, j, start = 0;
 4     memset(table, 0, sizeof(table));
 5     for (i = 0; s[i] != '\0'; ++i){
 6         if( (++table[s[i]]) == 2 ){
 7             if (currlen > maxlen){
 8                 maxlen = currlen;
 9             }
10             for(j = start; j < i; ++j){ //start記錄重復的字符後一個位置
11                 if (s[j] == s[i]){
12                     table[s[j]] = 1;
13                     start = j+1;
14                     break;
15                 }else{
16                     --currlen;
17                     table[s[j]] = 0;
18                 }
19             }
20         }else{
21             ++currlen;
22         }
23     }
24     if (currlen > maxlen){
25         maxlen = currlen;
26     }
27     return maxlen;
28 }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved