03.04. 化栈为队(简单)

1,问题描述

面试题 01.01. 判定字符是否唯一

难度:简单

实现一个算法,确定一个字符串 s 的所有字符是否全都不同。

示例 1:

1
2
输入: s = "leetcode"
输出: false

示例 2:

1
2
输入: s = "abc"
输出: true

限制:

  • 0 <= len(s) <= 100
  • s[i]仅包含小写字母
  • 如果你不使用额外的数据结构,会很加分。

2,初步思考

​ 栈的数据特性是:FILO,先进后出

​ 队列的数据特性是:FIFO,先进先出

直接安排一个备用栈用于整理数据即可

3,代码处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.ArrayDeque;
import java.util.Deque;

public class _面试题03_04化栈为队 {
}

class MyQueue {


Deque<Integer> stack = new ArrayDeque<>();// 数据存储
Deque<Integer> temp = new ArrayDeque<>();// 备胎

/**
* Initialize your data structure here.
*/
public MyQueue() {
}

/**
* Push element x to the back of queue.
*/
public void push(int x) {// 本质就是拿备胎来进行数据转移
if (stack.isEmpty()) {
stack.push(x);
return;
}
while (!stack.isEmpty()) {
temp.push(stack.pop());
}
temp.push(x);
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
}

/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
return stack.pop();
}

/**
* Get the front element.
*/
public int peek() {
return stack.peek();
}

/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return stack.isEmpty();
}
}