for _, tt := range tests { actual := LongNotReplace(tt.s) // 结果不等于设定的答案 if actual != tt.ans { t.Errorf("got %d for input %q, expected %d", actual, tt.s, tt.ans) } } }
// 性能测试 func BenchmarkSubstr(b *testing.B) { s := "acbsafaswwqabcdedg123adadwdcs" ans := 7; // 答案 for i := 0; i < 10; i++ { s += s } b.Logf("strlen:%d", len(s)) b.ResetTimer() // 重置当前执行时间,不计算上面拼接字符串 for i := 0; i < b.N; i++ { actual := LongNotReplace(s) if actual != ans { b.Errorf("got %d for input %q, expected %d", actual, s, ans) } } }
class Solution { public int lengthOfLongestSubstring(String s) { int maxLen = 0; int start = 0; HashMap<Character, Integer> lastOccurred = new HashMap<>(); char[] chars = s.toCharArray(); int charsLen = chars.length; for (int i = 0; i < charsLen; i++) { // 从 map 中获取元素,元素存在且元素出现在start开始的子串中则为重复 Integer lastI = lastOccurred.get(chars[i]); if (null != lastI && lastI >= start) { start = lastI + 1; } // 计算距离 int distance = i - start + 1; if (distance > maxLen) { maxLen = distance; } lastOccurred.put(chars[i], i); } return maxLen; } }