Apr 10

作者: 程序猪小羊 | 来源:发表于2018-04-12 06:58 被阅读12次

1. LeetCode题号3

题目内容:给定一个字符串,寻找没有字符重复的最长子字符串。

1. 初始方法:
  • 简单粗暴check所有满足条件的Substring——内部没有重复字符(Character),并且持续更新最长Substring长度。
    (用同一个maxLen记录最长字符串(从i = 0更新到i = len - 1))
    for (i = 0; i < len; i++){
    for (j = i, j <= len; j++){
    }
    }

  • public boolean inoOrNot()
    // check whether all the Characters in this Substring s is UNIQUE

  • 使用了Set API;

  • Substring [i, j]:check s.charAt(k) :
    if(set.add(s.charAt(k)))遇到重复的了,立刻返回false;
    否则,set.add(s.charAt(k)) - 加入这个没重复的,并且继续往下一个查找 k++, 直到k = j

  • 注意:
    j <= len && k < j
    || j < len && k <= j
    原因: // j <= len for i = len-1, s.charAt(len-1),
    // if the longest substring only contains one char
    // the length (j - i) should be 1;
    // therefore, j should be able to reach len

  • Hash Set 和 Hash Map?
    总结

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        // Set<Character> aSet = New HashSet<>();
        int maxLen = 0;
        
        // String a = new String("");
        // String b = new String("");
        
//         How to check every character in a String?
//         and do some comparisons, merge, or reorder? 
        for(int i = 0 ; i< len; i++){
            for (int j = i + 1; j <= len; j++){ 
                // j <= len for i = **len-1**, s.charAt(**len-1**), 
                // if the longest substring only contains one char
                //     the length (j - i) should be 1; 
                // therefore, j should be able to reach len
                if(inOrNot(s, i, j)){
                    maxLen = Math.max(maxLen, j-i);
                }
            }

            // Character temp = s.charAt(i)
            // if(!aSet.contains(temp)){
            //     aSet.add(temp);
            // }else{}
        }
        return maxLen;
    }
            
      public boolean inOrNot(String s, int start, int end) {
          Set<Character> set = new HashSet<>();
          for (int k = start; k < end; k++){
            Character ch = s.charAt(k);
            if (set.contains(ch)){
                return false;
            } else {
                set.add(ch);
            }
        }
        return true; 
    }
}

上面方法“Time Limit Exceeded”。

2. 优化:

  • Solution提到了Slide Window的方法。

遇到相同的字符,起点➕1,终点➕1. (窗口整体向后滑动一格。)

LeetCode题号5

题目内容:给定一个字符串,寻找最长的回文字子符串。

LeetCode题号14

题目内容:给定一个数组,数组中储存的元素为字符串,寻找这些字符串最长公共前缀。

本期会公布题号13的答案,接下去会慢慢更新,请大家多多支持。

相关文章

网友评论

      本文标题:Apr 10

      本文链接:https://www.haomeiwen.com/subject/ukcahftx.html