我正在做一个项目,我需要在SampleQueue
类中添加以下方法 - 。
public static boolean isValid(String s)
上面的方法应该这样做 - 它将一个字符串作为输入参数。考虑可以拆分的字符串,以便它们的前半部分与后半部分相同(忽略空格、标点符号和大小写)。例如,字符串“treetree”可以拆分为“tree”和“tree”。另一个例子是“世界,世界”。忽略空格和逗号后,字符串的两半是相同的。然而,字符串“kattan”有不相等的两半,字符串“abcab”也是如此。
基本上,当字符串具有上述属性时,我的方法应该返回 true,否则返回 false。我们只需要使用SampleQueue
类中的方法来实现该方法,如下所示:
public class SampleQueue<T> {
private T[] queue;
private int frontIndex;
private int backIndex;
private static final int DEFAULT_INITIAL_CAPACITY = 200;
public SampleQueue() {
this(DEFAULT_INITIAL_CAPACITY);
}
public SampleQueue(int initialCapacity) {
T[] tempQueue = (T[]) new Object[initialCapacity + 1];
queue = tempQueue;
frontIndex = 0;
backIndex = initialCapacity;
}
public void enqueue(T newEntry) {
ensureCapacity();
backIndex = (backIndex + 1) % queue.length;
queue[backIndex] = newEntry;
}
public T getFront() {
T front = null;
if (!isEmpty())
front = queue[frontIndex];
return front;
}
public T dequeue() {
// some stuff here
}
private void ensureCapacity() {
// some stuff here
}
public boolean isEmpty() {
// some stuff here
}
public void clear() {
// some stuff here
}
public static boolean isValid(String s) {
if (s == null || s.isEmpty()) {
return false;
}
SampleQueue<Character> myQueue = new SampleQueue<>();
for (char ch : s.trim().toLowerCase().toCharArray()) {
if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'))
myQueue.enqueue(ch);
}
// all is this right way to check the length?
if (myQueue.queue.length % 2 == 1) {
return false;
}
// now I am confuse here?
}
}
isValid
我根据我想出的这个逻辑在方法的基础上实现了一些东西,但是我对如何处理案例长度是偶数感到困惑?
一次将所有字符串的字符(不包括空格和标点符号)排入队列。设队列长度为n。如果 n 是奇数,则返回 false。如果 n 是偶数,我该怎么办?