leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

first-non-repeating.dart (816B)


      1 import 'dart:io';
      2 //This is a leetcode style question, but not from leetcode.
      3 //The idea is to find the first character of the input string that
      4 //does not repeat in the string. This is the optimized way using maps
      5 //which is linear time, but the simple solution would be brute force checking
      6 //every single charcter which would be O(n^2);
      7 void main(){
      8     stdout.write("Enter text to find the first non-repeating character: ");
      9     String s = stdin.readLineSync() ?? "N/A";
     10     Map<String,int> vals = {};
     11     for(int i = 0 ; i < s.length; ++i){
     12         vals[s[i]] = (vals[s[i]] ?? 0) + 1;
     13     }
     14     for(int i = 0 ; i < s.length ; ++i){
     15             if(vals[s[i]] == 1){
     16                 print(s[i] + " is the first character that does not repeat in the string.");
     17                 break;
     18             }
     19         }
     20     }