检查我们是否可以将字符串分为两个一半,两个半为相等



我正在从事一个项目,我需要在SampleQueue类中添加以下方法 -

public static boolean isValid(String s)

上面的方法应该这样做 - 它将以字符串作为输入 范围。考虑可以分开的字符串,以便上半年 与下半场相同(忽略空白,标点符号和 案件)。例如,字符串" Treetrey"可以分为"树",并且 "树"。另一个例子是"世界,世界"。忽略空白后 逗号,字符串的两个半是相同的。但是,那 字符串" kattan"有不等的一半,字符串" abcab"。

基本上,当字符串具有上面的属性和错误否则时,我的方法应返回true。如下所示,我们只需要在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。如果是 奇怪,返回false。如果n是我该怎么办?

这似乎过于复杂;使用A 正则表达式删除所有内容而不是字母,然后测试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()));
}

相关内容

最新更新