@@ -118,6 +118,44 @@ console.log("Binary Search: ", binarySearch(arr5, target2));
118
118
console . log ( "-------------------------------------------------" ) ;
119
119
console . log ( "Activity 3: " ) ;
120
120
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
+
121
159
console . log ( "-------------------------------------------------" ) ;
122
160
console . log ( "Activity 4: " ) ;
123
161
0 commit comments