java - 检查我们是否可以将字符串分成两半并且两半相等?

标签 java algorithm data-structures

我正在做一个项目,我需要在 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/

相关文章:

java - 如何使用我构建的模型在 Weka 中测试单个实例?

用于替换的 Java 正则表达式 - 如何使其高效

algorithm - 在行和列中查找具有相同编号的位置

algorithm - 用于在类别的二维网格中搜索坐标的最佳数据结构

c++ - 我应该如何在 C++ 中解释这个结构?

java - 计算以空格分隔的两个日期之间的 13 号星期五

java 。泛型类中的方法总是返回 Object

iphone - 检查 NSMutableArray 是否包含来自另一个数组的值

algorithm - 一个包含 100 万个整数的大文件,找到最常出现的整数的最快方法是什么?

c# - 小型集合的快速数据结构