class Solution {
public boolean repeatedSubstringPattern(String s) {
if (s.equals("")) return false;
int len = s.length();
s = " " + s;
char[] chars = s.toCharArray();
int[] next = new int[len+1]; //用于存储每个位置对应的前缀与后缀相同的最大长度
//构造next数组
for(int i = 2, j = 0; i <= len; i++){
//在 KMP 算法中,这一部分用于找到前缀与后缀相同的最大长度
//当当前字符与前缀的下一个字符不相同时,根据已计算的 next 数组回溯到上一个匹配的位置
while(j > 0 && chars[i] != chars[j+1]) j = next[j];
//如果当前字符与前缀的下一个字符相同,则将前缀与后缀相同的长度加一
if (chars[i] == chars[j+1]) j++;
//将当前位置的前缀与后缀相同的最大长度记录到 next 数组中
next[i] = j;
}
if (next[len] > 0 && len % (len - next[len]) == 0){
return true;
}
return false;
}
}
class Solution {
public int removeElement(int[] nums, int val) {
int slow = 0;
for ( int i = 0 ; i < nums.length ; i++){
if (nums[i] != val){
nums[slow] = nums[i];
slow++;
}
}
return slow;
}
}
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dumpstackIn();
return stackOut.pop();
}
public int peek() {
dumpstackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
private void dumpstackIn(){
if (!stackOut.isEmpty()) return;//return退出当前函数
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
//每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
public void push(int x) {
queue.offer(x); //添加一个元素并返回true
int size = queue.size();
//移动除了 A 的其它数
while (size-- > 1)
queue.offer(queue.poll()); //poll:移除并返问队列头部的元素
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}