美文网首页
JAVA实现xyBalance(codingbat)

JAVA实现xyBalance(codingbat)

作者: 修玛哦 | 来源:发表于2020-05-20 00:33 被阅读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().
    }
    
    

    相关文章

      网友评论

          本文标题:JAVA实现xyBalance(codingbat)

          本文链接:https://www.haomeiwen.com/subject/cuuwohtx.html