[Swift]LeetCode677. 键值映射 | Map Sum Pairs

Implement a MapSum class with insert, and sum methods.

For the method insert, you‘ll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.

For the method sum, you‘ll be given a string representing the prefix, and you need to return the sum of all the pairs‘ value whose key starts with the prefix.

Example 1:

Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5


实现一个 MapSum 类里的两个方法,insert 和 sum

对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。

对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。

示例 1:

输入: insert("apple", 3), 输出: Null
输入: sum("ap"), 输出: 3
输入: insert("app", 2), 输出: Null
输入: sum("ap"), 输出: 5


Runtime: 12 ms

Memory Usage: 19.9 MB

 1 class MapSum {
 2     var m:[String:[Int]]
 3
 4     /** Initialize your data structure here. */
 5     init() {
 6         m = [String:[Int]]()
 7     }
 8
 9     func insert(_ key: String, _ val: Int) {
10         var diff:Int = val - m[key,default:[0,0]][0]
11         var n:Int = key.count
12         m[key,default:[0,0]][0] = val
13         for i in stride(from:n - 1,to:0,by:-1)
14         {
15             m[key.subString(0, i),default:[0,0]][1] += diff
16         }
17     }
18
19     func sum(_ prefix: String) -> Int {
20         return m[prefix,default:[0,0]][0] + m[prefix,default:[0,0]][1]
21     }
22 }
23
24 extension String {
25     // 截取字符串:指定索引和字符数
26     // - begin: 开始截取处索引
27     // - count: 截取的字符数量
28     func subString(_ begin:Int,_ count:Int) -> String {
29         let start = self.index(self.startIndex, offsetBy: max(0, begin))
30         let end = self.index(self.startIndex, offsetBy:  min(self.count, begin + count))
31         return String(self[start..<end])
32     }
33 }
34
35 /**
36  * Your MapSum object will be instantiated and called as such:
37  * let obj = MapSum()
38  * obj.insert(key, val)
39  * let ret_2: Int = obj.sum(prefix)
40  */ 


16ms

 1 class MapSum {
 2     private let root = TrieNode()
 3
 4     /** Initialize your data structure here. */
 5     init() {
 6
 7     }
 8
 9     func insert(_ key: String, _ val: Int) {
10         var node = root
11         for c in key {
12             let next = node.insert(c, val)
13             node = next
14         }
15         node.sum = val
16     }
17
18     func sum(_ prefix: String) -> Int {
19         var node = root
20         for c in prefix {
21             guard let next = node.search(c) else {
22                 return 0
23             }
24             node = next
25         }
26         return node.allSum()
27     }
28 }
29
30 class TrieNode {
31
32     var sum = 0
33     private var map = [Character: TrieNode]()
34
35     func insert(_ c: Character, _ val: Int) -> TrieNode {
36         if let node = map[c] {
37             return node
38         }
39         let node = TrieNode()
40         map[c] = node
41         return node
42     }
43
44     func search(_ c: Character) -> TrieNode? {
45         return map[c]
46     }
47
48     func allSum() -> Int {
49         var val = sum
50         map.forEach {
51             val += $1.allSum()
52         }
53         return val
54     }
55 }


28ms

 1 class Node {
 2     var value: Character?
 3     var parent: Node?
 4     var children: [Character : Node] = [:]
 5     var sum: Int?
 6
 7     init(value: Character? = nil, parent: Node? = nil) {
 8         self.value = value
 9         self.parent = parent
10     }
11
12     func add(letter: Character) {
13         guard children[letter] == nil else { return }
14         children[letter] = Node(value: letter, parent: self)
15     }
16 }
17
18 class MapSum {
19     let root = Node()
20
21     init() {
22
23     }
24
25     func insert(_ key: String, _ val: Int) {
26         guard !key.isEmpty else { return }
27         var currentNode = root
28
29         for char in key {
30             currentNode.add(letter: char)
31             guard let node = currentNode.children[char] else { continue }
32             currentNode = node
33         }
34
35         currentNode.sum = val
36     }
37
38     func sum(_ prefix: String) -> Int {
39         guard !prefix.isEmpty else { return 0 }
40         var currentNode = root
41
42         for char in prefix {
43             if let node = currentNode.children[char] {
44                 currentNode = node
45             } else {
46                 return 0
47             }
48         }
49
50         return findWords(node: currentNode)
51     }
52
53     func findWords(node: Node) -> Int {
54         var result = 0
55
56         for child in node.children {
57             result +=  findWords(node: child.value)
58         }
59
60         return result + (node.sum ?? 0)
61     }
62 }

原文地址:https://www.cnblogs.com/strengthen/p/10498122.html

时间: 2024-10-08 06:00:11

[Swift]LeetCode677. 键值映射 | Map Sum Pairs的相关文章

Java记录 -63- Java的键值映射Map

public interface Map<K,V> 将键映射到值的对象.一个映射不能包含重复的键:每个键最多只能映射到一个值. Map接口取代 Dictionary 类,后者完全是一个抽象类,而不是一个接口. Map 接口提供三种collection 视图,允许以键集.值集或键-值映射关系集的形式查看某个映射的内容.映射顺序 定义为迭代器在映射的 collection 视图上返回其元素的顺序.某些映射实现可明确保证其顺序,如 TreeMap 类:另一些映射实现则不保证顺序,如 HashMap 

Android : 输入设备键值映射流程

一.Android输入子系统简介: Android输入事件的源头是位于/dev/input/下的设备节点,而输入系统的终点是由WMS管理的某个窗口.最初的输入事件为内核生成的原始事件,而最终交付给窗口的则是KeyEvent或MotionEvent对象.因此Android输入系统的主要工作是读取设备节点中的原始事件,将其加工封装,然后派发给一个特定的窗口以及窗口中的控件.这个过程由InputManagerService(以下简称IMS)系统服务为核心的多个参与者共同完成. 图1:输入系统的总体流程

LC 677. Map Sum Pairs

Implement a MapSum class with insert, and sum methods. For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pai

LeetCode 677. Map Sum Pairs 键值映射(C++/Java)

题目: Implement a MapSum class with insert, and sum methods. For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value

javascript 实现键值对 &quot;map&quot;

//javascript 没有map,但是有map功能-_-! 自己动手,丰衣足食 (function(){ try{ function Directory(){ this.key = new Array(); this.value = new Array(); } //添加 Directory.prototype.add = function(key,value){ //key是否和已经存在的key重复 for(var i=0;i<this.key.length;i++){ if(this.k

leetcode 677. Map Sum Pairs

使用前缀树 function Node() { this.value = 0 this.children = {} } class MapSum { constructor() { this.root = new Node() } insert(word, val) { var node = this.root; for (let next of word) { if (!node.children[next]) { node.children[next] = new Node() } node

用字典给Model赋值并支持map键值替换

这个是昨天教程的升级版本,支持键值的map替换. 源码如下: NSObject+Properties.h 与 NSObject+Properties.m // // NSObject+Properties.h // // Created by YouXianMing on 14-9-4. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interface

Android4.0 添加一个新的Android 键值

这里添加新的键值,不是毫无凭据凭空创造的一个键值,而是根据kernel中检测到的按键值,然后转化为Android所需要的数值: 以添加一个linux键值为217,把它映射为android的键值Browser(这个键值之前不存在)为例介绍一下: 1.android之前没有这个键值,需要定义 /frameworks/base/core/java/android/view/KeyEvent.java //定义这个新的键值 public static final int KEYCODE_BROWSER

[PY3]——字典中的键如何映射多个值?字典如何排序?

Defaultdict 默认字典 collections 模块中的 defaultdict(默认字典),可以用来构造“一个键映射多个值”这样的字典 如果你想保持元素的插入顺序就应该使用list, 如果想去掉重复元素就使用set import collections import defaultdict d=defaultdict(list) / e=defaultdict(set) d = { 'a' : [1, 2, 3], 'b' : [4, 5] } e = { 'a' : {1, 2,