Add solution 1656、1657

This commit is contained in:
YDZ
2020-11-20 23:35:30 +08:00
parent 91e1a92cdd
commit 35c39173bc
10 changed files with 542 additions and 162 deletions

View File

@ -1,9 +1,5 @@
package leetcode
import (
"fmt"
)
type OrderedStream struct {
ptr int
stream []string
@ -17,7 +13,6 @@ func Constructor(n int) OrderedStream {
func (this *OrderedStream) Insert(id int, value string) []string {
this.stream[id] = value
res := []string{}
fmt.Printf("%v %v %v\n", this.ptr, id, value)
if this.ptr == id || this.stream[this.ptr] != "" {
res = append(res, this.stream[this.ptr])
for i := id + 1; i < len(this.stream); i++ {

View File

@ -5,7 +5,7 @@ import (
"testing"
)
func Test_Problem707(t *testing.T) {
func Test_Problem1656(t *testing.T) {
obj := Constructor(5)
fmt.Printf("obj = %v\n", obj)
param1 := obj.Insert(3, "ccccc")

View File

@ -0,0 +1,106 @@
# [1656. Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream/)
## 题目
There is a stream of `n` `(id, value)` pairs arriving in an **arbitrary** order, where `id` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values.
Implement the `OrderedStream` class:
- `OrderedStream(int n)` Constructs the stream to take `n` values.
- `String[] insert(int id, String value)` Inserts the pair `(id, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order.
**Example:**
![https://assets.leetcode.com/uploads/2020/11/10/q1.gif](https://assets.leetcode.com/uploads/2020/11/10/q1.gif)
```
Input
["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
Output
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]
Explanation
// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns [].
os.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"].
os.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].
os.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns [].
os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"].
// Concatentating all the chunks returned:
// [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]
// The resulting order is the same as the order above.
```
**Constraints:**
- `1 <= n <= 1000`
- `1 <= id <= n`
- `value.length == 5`
- `value` consists only of lowercase letters.
- Each call to `insert` will have a unique `id.`
- Exactly `n` calls will be made to `insert`.
## 题目大意
有 n 个 (id, value) 对,其中 id 是 1 到 n 之间的一个整数value 是一个字符串。不存在 id 相同的两个 (id, value) 对。
设计一个流,以 任意 顺序获取 n  (id, value) 对,并在多次调用时 按 id 递增的顺序 返回一些值。
实现 OrderedStream 类:
- OrderedStream(int n) 构造一个能接收 n 个值的流,并将当前指针 ptr 设为 1 。
- String[] insert(int id, String value) 向流中存储新的 (id, value) 对。存储后:
如果流存储有 id = ptr 的 (id, value) 对,则找出从 id = ptr 开始的 最长 id 连续递增序列 ,并 按顺序 返回与这些 id 关联的值的列表。然后,将 ptr 更新为最后那个 id + 1 
否则,返回一个空列表。
## 解题思路
- 设计一个具有插入操作的 Ordered Stream。insert 操作先在指定位置插入 value然后返回当前指针 ptr 到最近一个空位置的最长连续递增字符串。如果字符串不为空ptr 移动到非空 value 的后一个下标位置处。
- 简单题。按照题目描述模拟即可。注意控制好 ptr 的位置。
## 代码
```go
package leetcode
type OrderedStream struct {
ptr int
stream []string
}
func Constructor(n int) OrderedStream {
ptr, stream := 1, make([]string, n+1)
return OrderedStream{ptr: ptr, stream: stream}
}
func (this *OrderedStream) Insert(id int, value string) []string {
this.stream[id] = value
res := []string{}
if this.ptr == id || this.stream[this.ptr] != "" {
res = append(res, this.stream[this.ptr])
for i := id + 1; i < len(this.stream); i++ {
if this.stream[i] != "" {
res = append(res, this.stream[i])
} else {
this.ptr = i
return res
}
}
}
if len(res) > 0 {
return res
}
return []string{}
}
/**
* Your OrderedStream object will be instantiated and called as such:
* obj := Constructor(n);
* param_1 := obj.Insert(id,value);
*/
```

View File

@ -0,0 +1,33 @@
package leetcode
import (
"sort"
)
func closeStrings(word1 string, word2 string) bool {
if len(word1) != len(word2) {
return false
}
freqCount1, freqCount2 := make([]int, 26), make([]int, 26)
for _, c := range word1 {
freqCount1[c-97]++
}
for _, c := range word2 {
freqCount2[c-97]++
}
for i := 0; i < 26; i++ {
if (freqCount1[i] == freqCount2[i]) ||
(freqCount1[i] > 0 && freqCount2[i] > 0) {
continue
}
return false
}
sort.Ints(freqCount1)
sort.Ints(freqCount2)
for i := 0; i < 26; i++ {
if freqCount1[i] != freqCount2[i] {
return false
}
}
return true
}

View File

@ -0,0 +1,68 @@
package leetcode
import (
"fmt"
"testing"
)
type question1657 struct {
para1657
ans1657
}
// para 是参数
// one 代表第一个参数
type para1657 struct {
word1 string
word2 string
}
// ans 是答案
// one 代表第一个答案
type ans1657 struct {
one bool
}
func Test_Problem1657(t *testing.T) {
qs := []question1657{
{
para1657{"abc", "bca"},
ans1657{true},
},
{
para1657{"a", "aa"},
ans1657{false},
},
{
para1657{"cabbba", "abbccc"},
ans1657{true},
},
{
para1657{"cabbba", "aabbss"},
ans1657{false},
},
{
para1657{"uau", "ssx"},
ans1657{false},
},
{
para1657{"uuukuuuukkuusuususuuuukuskuusuuusuusuuuuuuk", "kssskkskkskssskksskskksssssksskksskskksksuu"},
ans1657{false},
},
}
fmt.Printf("------------------------Leetcode Problem 1657------------------------\n")
for _, q := range qs {
_, p := q.ans1657, q.para1657
fmt.Printf("【input】:%v 【output】:%v \n", p, closeStrings(p.word1, p.word2))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,114 @@
# [1657. Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/)
## 题目
Two strings are considered **close** if you can attain one from the other using the following operations:
- Operation 1: Swap any two **existing** characters.
- For example, `abcde -> aecdb`
- Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and do the same with the other character.
- For example, `aacabb -> bbcbaa` (all `a`'s turn into `b`'s, and all `b`'s turn into `a`'s)
You can use the operations on either string as many times as necessary.
Given two strings, `word1` and `word2`, return `true` *if* `word1` *and* `word2` *are **close**, and* `false` *otherwise.*
**Example 1:**
```
Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"
```
**Example 2:**
```
Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
```
**Example 3:**
```
Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"
```
**Example 4:**
```
Input: word1 = "cabbba", word2 = "aabbss"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any amount of operations.
```
**Constraints:**
- `1 <= word1.length, word2.length <= 105`
- `word1` and `word2` contain only lowercase English letters.
## 题目大意
如果可以使用以下操作从一个字符串得到另一个字符串,则认为两个字符串 接近
- 操作 1交换任意两个 现有 字符。例如abcde -> aecdb
- 操作 2将一个 现有 字符的每次出现转换为另一个 现有 字符并对另一个字符执行相同的操作。例如aacabb -> bbcbaa所有 a 转化为 b ,而所有的 b 转换为 a
你可以根据需要对任意一个字符串多次使用这两种操作。给你两个字符串word1 和 word2 。如果 word1 和 word2 接近 ,就返回 true ;否则,返回 false 。
## 解题思路
- 判断 2 个字符串是否“接近”。“接近”的定义是能否通过交换 2 个字符或者 2 个字母互换,从一个字符串变换成另外一个字符串,如果存在这样的变换,即是“接近”。
- 先统计 2 个字符串的 26 个字母的频次,如果频次有不相同的,直接返回 false。在频次相同的情况下再从小到大排序再次扫描判断频次是否相同。
- 注意几种特殊情况:频次相同,再判断字母交换是否合法存在,如果字母不存在,输出 false。例如测试文件中的 case 5 。出现频次个数相同,但是频次不同。例如测试文件中的 case 6 。
## 代码
```go
package leetcode
import (
"sort"
)
func closeStrings(word1 string, word2 string) bool {
if len(word1) != len(word2) {
return false
}
freqCount1, freqCount2 := make([]int, 26), make([]int, 26)
for _, c := range word1 {
freqCount1[c-97]++
}
for _, c := range word2 {
freqCount2[c-97]++
}
for i := 0; i < 26; i++ {
if (freqCount1[i] == freqCount2[i]) ||
(freqCount1[i] > 0 && freqCount2[i] > 0) {
continue
}
return false
}
sort.Ints(freqCount1)
sort.Ints(freqCount2)
for i := 0; i < 26; i++ {
if freqCount1[i] != freqCount2[i] {
return false
}
}
return true
}
```

View File

@ -1,88 +0,0 @@
package leetcode
import (
"sort"
)
func closeStrings(word1 string, word2 string) bool {
if len(word1) != len(word2) {
return false
}
freqWord1, freq1, freqList1, freqWord2, freq2, freqList2, flag := map[byte]int{}, []int{}, map[int][]byte{}, map[byte]int{}, []int{}, map[int][]byte{}, false
for i := 0; i < len(word1); i++ {
freqWord1[word1[i]]++
}
for i := 0; i < len(word2); i++ {
freqWord2[word2[i]]++
}
freqTemp1 := map[int]int{}
for k, v := range freqWord1 {
freqTemp1[v]++
if list, ok := freqList1[v]; ok {
list = append(list, k)
freqList1[v] = list
} else {
list := []byte{}
list = append(list, k)
freqList1[v] = list
}
}
for _, v := range freqTemp1 {
freq1 = append(freq1, v)
}
freqTemp2 := map[int]int{}
for k, v := range freqWord2 {
freqTemp2[v]++
if list, ok := freqList2[v]; ok {
list = append(list, k)
freqList2[v] = list
} else {
list := []byte{}
list = append(list, k)
freqList2[v] = list
}
}
for _, v := range freqTemp2 {
freq2 = append(freq2, v)
}
if len(freq1) != len(freq2) {
return false
}
sort.Ints(freq1)
sort.Ints(freq2)
for i := 0; i < len(freq1); i++ {
if freq1[i] != freq2[i] {
flag = true
break
}
}
if flag == true {
return false
}
flag = false
// 频次相同,再判断字母交换是否合法存在
for k, v := range freqWord1 {
if list, ok := freqList2[v]; ok {
for i := 0; i < len(list); i++ {
if list[i] != k && list[i] != '0' {
// 交换的字母不存在
if _, ok := freqWord1[list[i]]; !ok {
flag = true
break
} else {
// 交换的字母存在,重置这一位,代表这一个字母被交换了,下次不用它
list[i] = '0'
}
}
}
} else {
// 出现频次个数相同,但是频次不同
flag = true
break
}
}
if flag == true {
return false
}
return true
}

View File

@ -1,68 +0,0 @@
package leetcode
import (
"fmt"
"testing"
)
type question1649 struct {
para1649
ans1649
}
// para 是参数
// one 代表第一个参数
type para1649 struct {
word1 string
word2 string
}
// ans 是答案
// one 代表第一个答案
type ans1649 struct {
one bool
}
func Test_Problem1649(t *testing.T) {
qs := []question1649{
{
para1649{"abc", "bca"},
ans1649{true},
},
{
para1649{"a", "aa"},
ans1649{false},
},
{
para1649{"cabbba", "abbccc"},
ans1649{true},
},
{
para1649{"cabbba", "aabbss"},
ans1649{false},
},
{
para1649{"uau", "ssx"},
ans1649{false},
},
{
para1649{"uuukuuuukkuusuususuuuukuskuusuuusuusuuuuuuk", "kssskkskkskssskksskskksssssksskksskskksksuu"},
ans1649{false},
},
}
fmt.Printf("------------------------Leetcode Problem 1649------------------------\n")
for _, q := range qs {
_, p := q.ans1649, q.para1649
fmt.Printf("【input】:%v 【output】:%v \n", p, closeStrings(p.word1, p.word2))
}
fmt.Printf("\n\n\n")
}