【问题标题】:check whether we can split string in two half and both halfves are equal?检查我们是否可以将字符串分成两半并且两半相等?
【发布时间】:2019-07-24 01:55:57
【问题描述】:

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

public static boolean isValid(String s)

上面的方法应该这样做 - 它将一个字符串作为输入 范围。考虑可以拆分的字符串,以便它们的前半部分 与它们的后半部分相同(忽略空格、标点符号和 案子)。例如,字符串“treetree”可以拆分为“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 是 奇怪,返回假。如果 n 是偶数,我该怎么办?

【问题讨论】:

    标签: java algorithm data-structures


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 2015-12-02
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多