Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1f605c1

Browse files
length of unique substring and container with most water
1 parent fd0eb3a commit 1f605c1

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎src/ArraysAndStrings/FiftyQuestions.java‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,54 @@ else if (target <= nums[right]) {
219219
}
220220
}
221221

222+
/**
223+
* longest substring without repeating characters
224+
* */
225+
226+
public static int lengthOfLongestSubstring(String s) {
227+
// a b c a b c b b
228+
// 0 1 2 3 4 5 6 7
229+
if (s.length() <= 1)
230+
return s.length();
231+
Map<Character, Integer> seenCharacters = new HashMap<>();
232+
int left = 0, longest = 0;
233+
for (int right = 0; right < s.length(); right++) {
234+
char currentChar = s.charAt(right);
235+
if (null != seenCharacters.get(currentChar) && seenCharacters.get(currentChar) >= left) {
236+
left = seenCharacters.get(currentChar) + 1;
237+
}
238+
longest = Math.max(longest, right-left+1);
239+
seenCharacters.put(currentChar, right);
240+
}
241+
242+
return longest;
243+
244+
}
245+
246+
/**
247+
* Container with largest amount of water
248+
* concept - 2 shifting pointers
249+
*/
250+
public static int maxArea(int[] height) {
251+
252+
if (height.length <= 1) return 0;
253+
254+
int left = 0;
255+
int right = height.length - 1;
256+
int maxArea = 0;
257+
258+
while (left <= right) {
259+
int leftNum = height[left];
260+
int rightNum = height[right];
261+
262+
maxArea = Math.max(maxArea, Math.min(leftNum, rightNum) * (right-left));
263+
if (leftNum < rightNum) left++;
264+
else right--;
265+
}
266+
267+
return maxArea;
268+
}
269+
222270
public static void main(String[] args) {
223271
int index = search(new int[]{2,2,2,3,4,2}, 3, 0, 5);
224272
System.out.println("index of 3 is " + index);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /