我正在做一个项目,我需要在 SampleQueue
类中添加以下方法 - 。
public static boolean isValid(String s)
Above method should do this - It will take a String as an input parameter. Consider strings that can be split so that their first half is the same as their second half (ignoring blanks, punctuation, and case). For example, the string "treetree" can be split into "tree" and "tree". Another example is "world, world". After ignoring blanks and the comma, the two halves of the string are the same. However, the string "kattan" has unequal halves, as does the string "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
方法中实现了一些东西,但我对如何处理长度为偶数的情况感到困惑?
Enqueue all of the string’s characters—excluding blanks and punctuation—one at a time. Let the length of the queue be n. If n is odd, return false. If n is even then what should I do?
最佳答案
这看起来太复杂了;使用正则表达式 删除除字母以外的所有内容,然后测试String
的两半是否相等。喜欢,
public static boolean isValid(String s) {
String t = s.replaceAll("[^A-Za-z]", "");
return t.substring(0, t.length() / 2).equals(t.substring(t.length() / 2, t.length()));
}
关于java - 检查我们是否可以将字符串分成两半并且两半相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54954696/