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 7de5e5d

Browse files
Chore: Completed Activity-3 for Day-18
1 parent 052e75c commit 7de5e5d

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎Day18/index.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,44 @@ console.log("Binary Search: ", binarySearch(arr5, target2));
118118
console.log("-------------------------------------------------");
119119
console.log("Activity 3: ");
120120

121+
// Write a function to count the occurrences of each character in a string. Log the character counts.
122+
123+
const countCharacters = (str) => {
124+
let charCount = {};
125+
for (let char of str) {
126+
if (charCount[char]) {
127+
charCount[char]++;
128+
} else {
129+
charCount[char] = 1;
130+
}
131+
}
132+
return charCount;
133+
}
134+
135+
let str = "hello";
136+
console.log("Character Count: ", countCharacters(str));
137+
138+
// Task 7: Write a function to find the longest substring without repeating characters in a string. Log the length of the substring.
139+
140+
const longestSubstring = (str) => {
141+
let longest = 0;
142+
let start = 0;
143+
let charIndex = {};
144+
145+
for (let i = 0; i < str.length; i++) {
146+
let char = str[i];
147+
if (charIndex[char] >= start) {
148+
start = charIndex[char] + 1;
149+
}
150+
charIndex[char] = i;
151+
longest = Math.max(longest, i - start + 1);
152+
}
153+
return longest;
154+
}
155+
156+
let str2 = "abcabcbb";
157+
console.log("Longest Substring: ", longestSubstring(str2));
158+
121159
console.log("-------------------------------------------------");
122160
console.log("Activity 4: ");
123161

0 commit comments

Comments
(0)

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