我正在为周一的面试做准备,发现了一个需要解决的问题,名为 "String Reduction"。该问题陈述如下:
给定一个由a、b和c组成的字符串,我们可以执行以下操作:取任意两个相邻且不同的字符,并用第三个字符替换它。例如,如果'a'和'c'相邻,则可以用'b'替换它们。通过重复应用此操作,得到最小的字符串是什么?
例如,cab -> cc或cab -> bb,结果为长度为2的字符串。对于这个问题,一个最优解是:bcab -> aab -> ac -> b。不能再应用更多操作,而且结果字符串的长度为1。 如果字符串=C CCCC,则无法执行任何操作,因此答案是5。
我在stackoverflow上看到了很多问题和答案,但我想验证自己的算法。这是我的伪代码算法。在我的代码中
- S is my string to reduce
- S[i] is the character at index i
- P is a stack:
redux is the function that reduces the characters.
function reduction(S[1..n]){ P = create_empty_stack(); for i = 1 to n do car = S[i]; while (notEmpty(P)) do head = peek(p); if( head == car) break; else { popped = pop(P); car = redux (car, popped); } done push(car) done return size(P)}
i = 1 :
car = S[i] = a, P = {∅}
P is empty, P = P U {car} -> P = {a}
i = 2 :
car = S[i] = b, P = {a}
P is not empty :
head = a
head != car ->
popped = Pop(P) = a
car = reduction (car, popped) = reduction (a,b) = c
P = {∅}
push(car, P) -> P = {c}
i = 3 :
car = S[i] = a, P = {c}
P is not empty :
head = c
head != car ->
popped = Pop(P) = c
car = reduction (car, popped) = reduction (a,c) = b
P = {∅}
push(car, P) -> P = {b}
...
i = 5 : (interesting case)
car = S[i] = c, P = {c}
P is not empty :
head = c
head == car -> break
push(car, P) -> P = {c, c}
i = 6 :
car = S[i] = b, P = {c, c}
P is not empty :
head = c
head != car ->
popped = Pop(P) = c
car = reduction (car, popped) = reduction (b,c) = a
P = {c}
P is not empty : // (note in this case car = a)
head = c
head != car ->
popped = Pop(P) = c
car = reduction (car, popped) = reduction (a,c) = b
P = {∅}
push(car, P) -> P = {b}
... and it continues until n
我已经在各种类似的示例上运行了此算法,它似乎有效。 我用Java编写了一个测试该算法的代码,当我将代码提交到系统时,我得到了错误的答案。 我已经在gisthub上发布了Java代码,这样你就可以看到它。
有人能告诉我我的算法有什么问题吗?
O(n)
的算法... - UmNyobe