JAVA实现xyBalance(codingbat)

2020-05-20  本文已影响0人  修玛哦

题目如下

We'll say that a String is xy-balanced if for all the 'x' chars in the string, there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return true if the given string is xy-balanced.

xyBalance("aaxbby") → true
xyBalance("aaxbb") → false
xyBalance("yaaxbb") → false

我的代码

/**
此题可简化为判别y是否比x更靠近右,巧妙运用indexOf()方法中,不存在则返回-1的特性实现如下代码:
*/
public boolean xyBalance(String str) {
  int xIndex = str.lastIndexOf("x");//找到最右边的x
  int yIndex = str.lastIndexOf("y");//找到最右边的y
  return yIndex>=xIndex;//判断y是否在x的右边。
}

官方solution

public boolean xyBalance(String str) {
  // Find the rightmost y
  int y = -1;
  for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i)=='y') y = i;
  }
  
  // Look at the x's, return false if one is after y
  for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i)=='x' && i > y) return false;
  }
  return true;

  // Solution notes: this solution uses two loops, each written the simple
  // 0..length way. You could do it with a single reverse loop, noticing
  // if you see an x before a y. Or use lastIndexOf().
}

上一篇下一篇

猜你喜欢

热点阅读