-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Backspace String Compare #43
base: main
Are you sure you want to change the base?
Conversation
後ろから見ていく方法は追加の空間が必要なくなるが、実装が複雑になる。 | ||
個人的には必要がなければできるだけスタックを使ってシンプルに実装する方が良いと思っている。 | ||
*/ | ||
func backspaceCompareStep1(s string, t string) bool { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
この解法が一番シンプルに感じました。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
これが一番いいように思いますね。変わったことをしたいならば Goroutine はどうですか。
func iterateReverse(s []rune, c chan rune) {
defer close(c)
backspaceCount := 0
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '#' {
backspaceCount++
} else if backspaceCount > 0 {
backspaceCount--
} else {
c <- s[i]
}
}
}
func backspaceCompare(s string, t string) bool {
cs := make(chan rune)
ct := make(chan rune)
go iterateReverse([]rune(s), cs)
go iterateReverse([]rune(t), ct)
for vs := range cs {
vt, ok := <-ct
if !ok || vs != vt {
return false
}
}
if _, ok := <-ct; ok {
return false
}
return true
}```
i, j := len(runeS)-1, len(runeT)-1 | ||
for i >= 0 || j >= 0 { | ||
i, j = nextIndex(runeS, i), nextIndex(runeT, j) | ||
if i >= 0 && j >= 0 && runeS[i] == runeT[j] { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i >= 0 && j >= 0
が 2 回登場しているなど、ループ内の処理の流れの見通しが悪く感じました。処理の順番を変えたほうがすっきりすると思います。
自分は Go 言語を書けないため、 C++ で書きますが、
class Solution {
public:
bool backspaceCompare(string s, string t) {
int s_index = ProcessBackspace(s.size() - 1, s);
int t_index = ProcessBackspace(t.size() - 1, t);
while (s_index >= 0 && t_index >= 0) {
if (s[s_index] != t[t_index]) {
return false;
}
s_index = ProcessBackspace(s_index - 1, s);
t_index = ProcessBackspace(t_index - 1, t);
}
return s_index < 0 && t_index < 0;
}
int ProcessBackspace(int index, const string& s) {
int num_backspaces = 0;
while (index >= 0) {
if (s[index] == '#') {
++num_backspaces;
--index;
continue;
}
if (num_backspaces > 0) {
--num_backspaces;
--index;
continue;
}
break;
}
return index;
}
};
はいかがでしょうか?
Backspace String Compareを解きました。レビューをお願い致します。
問題:https://leetcode.com/problems/backspace-string-compare/
言語:Go
すでに解いている方々:
Kitaken0107/GrindEasy#21