Leetcode c语言-Longest Substring Without Repeating Characters

Title:

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 subsequenceand not a substring.


题目是从一个字符串中找到最长的没有重复字符的子字符串。这道题目比较简单,就不多说解题思路,直接贴上c代码:


Solutions:

int lengthOfLongestSubstring(char* s) {
    int len = 0;
    int length = 1;
    int last_length = 1;
    int i;
    
    while (s[len]) {
        if (len >= 1) {
           for (i = len - length; i <= len -1; i++) {
               if (s[len] == s[i]) {
                   if (last_length < length)
                        last_length = length;
                                  
                   length = len -i;
                   break;
               }
               else if (i == len -1) {
                   length++;
                   if (last_length < length)
                        last_length = length;
               }
           } 
        }
        len++;
    }
    
    if (len == 0)
        return len;
    
    return last_length;

}


posted on 2017-09-09 11:30  sichenzhao  阅读(131)  评论(0编辑  收藏  举报

导航