博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 387: First Unique Character in a String
阅读量:4309 次
发布时间:2019-06-06

本文共 1676 字,大约阅读时间需要 5 分钟。

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"return 0.s = "loveleetcode",return 2.

 

Note: You may assume the string contain only lowercase letters.

 

1 public class Solution { 2     public int FirstUniqChar(string s) { 3         var dict = new Dictionary
>(); 4 // Map 5 for (int i = 0; i < s.Length; i++) 6 { 7 if (!dict.ContainsKey(s[i])) 8 { 9 dict[s[i]] = new List
();10 }11 12 dict[s[i]].Add(i); 13 }14        // Reduce15 bool found = false;16 var result = Int32.MaxValue;17 foreach (var pair in dict)18 {19 if (pair.Value.Count == 1 && pair.Value[0] < result)20 {21 found = true;22 result = pair.Value[0];23 }24 }25 26 return found ? result : -1;27 }28 }29 30 // traverse the string twice, if the string is super long, performance wouldn't be very good31 public class Solution1 {32 public int FirstUniqChar(string s) {33 var dict = new Dictionary
();34 35 foreach (var c in s)36 {37 if (!dict.ContainsKey(c))38 {39 dict[c] = 1;40 }41 else42 {43 dict[c]++;44 }45 }46 47 for (int i = 0; i < s.Length; i++)48 {49 if (dict[s[i]] == 1)50 {51 return i;52 }53 }54 55 return -1;56 }57 }

 

Follow up: what if the string is exetremly long and you have to process it with multi machines?

Answer: I think this is a typical Map-Reduce problem where you can split the string to multi batches, the Map function will be similar as my solution 1, one difference is we should pass the start index of each patch in the original string to the Map function, then the Reduce function will aggregate the Map results and generate the final result.

转载于:https://www.cnblogs.com/liangmou/p/8241316.html

你可能感兴趣的文章
MongoDB基本语法和操作入门
查看>>
学习笔记_vnpy实战培训day04_作业
查看>>
OCO订单(委托)
查看>>
学习笔记_vnpy实战培训day06
查看>>
回测引擎代码分析流程图
查看>>
Excel 如何制作时间轴
查看>>
股票网格交易策略
查看>>
matplotlib绘图跳过时间段的处理方案
查看>>
vnpy学习_04回测评价指标的缺陷
查看>>
ubuntu终端一次多条命令方法和区别
查看>>
python之偏函数
查看>>
vnpy学习_06回测结果可视化改进
查看>>
读书笔记_量化交易如何建立自己的算法交易01
查看>>
设计模式03_工厂
查看>>
设计模式04_抽象工厂
查看>>
设计模式05_单例
查看>>
设计模式06_原型
查看>>
设计模式07_建造者
查看>>
设计模式08_适配器
查看>>
设计模式09_代理模式
查看>>