【问题标题】:Lowercase 'g' in a string is "happy" if there is another 'g' immediately next to it如果字符串中的小写“g”紧挨着另一个“g”,则它是“快乐的”
【发布时间】:2015-08-20 00:40:41
【问题描述】:

如果旁边有另一个'g',我需要实现字符串中的小写'g' 是“快乐”的代码。然后,如果给定字符串中的所有g's 都满意,则返回true。例如:

gHappy("xxggxx") → 真
gHappy("xxgxx") → 假
gHappy("xxggyygxx") → false

这是我试过的代码:

public boolean gHappy(String str) {
  if(str.length() < 1){
     return false;
  }

  boolean result = false;
  for(int i = 1; i < str.length() - 1; i++){
     if(str.charAt(i) == 'g' && str.charAt(i - 1) == 'g' 
     || str.charAt(i + 1) == 'g'){
        result = true;

     }
  }

  return result;
}

但我没有通过一些测试用例,例如:

gHappy("gg") → 应该是true → 得到false
gHappy("xxgggxyg") → 应该是false → 得到true

【问题讨论】:

  • 可能是运算符优先级问题,&& vs ||但我不确定。尝试将条件括在括号中。 if 1 && (2||3) 看看会发生什么
  • 或者,颠倒你的逻辑,对任何失败的情况立即返回 false,否则返回 true。
  • 另外,1 不小于 2-1。
  • str.contains("gg")??

标签: java string


【解决方案1】:

如果角色是g,你可以先设置条件,然后你会 如果两者都不是'g',则比较它的前一个和下一个字符 标记变量 false 并退出循环。你必须再检查一个 条件如果单个“g”出现在字符串的最后一个索引处,如“xxgggxyg”,那么 你应该检查 (i == str.length()-2) && (str.charAt(i+1) == 'g') && (str.charAt(i) != 'g')

public boolean gHappy(String str) {
boolean flag = true;
if(str == "") return flag;

if(str.length() <= 2 && !str.equals("gg")) {
return false;
}

for(int i = 1; i < str.length()-1; i++)
{
  if(str.charAt(i) == 'g')
  {
    if(!(str.charAt(i-1) == 'g' || str.charAt(i+1) == 'g'))
    {
      flag = false;
      break;
    }
  }
  else if((i == str.length()-2) && (str.charAt(i+1) == 'g') && 
  (str.charAt(i) != 'g'))
  {
     flag = false;
     break;
  }
  }
  return flag;
  }

【讨论】:

    【解决方案2】:

    我会将快乐角色的概念提取到一个函数中,然后遍历所有调用检查的角色,如果有任何不快乐的角色,则退出。

    类似的东西。

    boolean isCharcterHappy(String s, int index) {
        if(s.charAt(index)!='g')
          return true;
        if(index>0 && s.charAt(index-1)=='g')
          return true;
        if(index<s.size()-1 && s.charAt(index+1)=='g')
          return true;
        return false;
    }
    
    public boolean gHappy(String str) {
      for(int i=0; i<str.size(); ++i) {
       if(!isCharcterHappy(str,i))
         return false;
      }
      return true;
    }
    

    【讨论】:

      【解决方案3】:

      我创建了一个gHappy 函数来验证给定字符串是否对某个字符感到满意。

      public boolean gHappy(String str, char chr) {
          for(int i = 0; i < str.length(); i++) {
              char cmp = str.charAt(i);
      
              if(cmp == chr && i < (str.length() - 1) && str.charAt(i+1) == chr)
                  // Found the character and the same character is at it's right
                  i++; // Little optimization, next character is the same so is automatically surrounded by the character.
              else if(cmp == chr && i > 0 && str.charAt(i-1) == chr) // Not at our right, maybe at our left?
                  continue;
              else if(cmp == chr) // Not left nor right, this character is unhappy !
                  return false;
          }
      
          return true;
      }
      

      当在当前字符的右侧找到相同的字符时,请注意小优化。因为什么时候可以确定 char 也会很高兴(因为我们是同一个 char 并且坐在字符串的左侧)我们不再需要检查它,因此i++

      【讨论】:

        【解决方案4】:

        看,正则表达式的力量!

        public boolean gHappy(String input) {
            // make sure input matches two g's in a row, but not a lone g
            return input.matches(".*gg.*") && !input.matches(".*(?<!g)g(?!g).*");
        }
        

        演示:http://ideone.com/Spq2hd

        【讨论】:

          【解决方案5】:

          你的 for 循环从 1 开始,当 i 不小于字符串的长度减去 1 时结束。 (str.length() - 1) 所以“gg”甚至不会运行循环。

          对于“xxgggxyg”,当您的程序看到 ggg 时,您的布尔值设置为 true,但您应该在最后点击“yg”后将其设置为 false。

          你可能想做喜欢(这个&&这个)|| (this && this) 而不是 (this && this) ||这个。

          【讨论】:

            【解决方案6】:

            这是我的解决方案。它有点笨拙,但只有在绝对必要时才会循环。大家觉得呢?

            public boolean gHappy(String str) {
                  if (str.indexOf('g') != -1)
                  {
                    //If string length is three or above
                    if (str.length() >= 3)
                    {
                      //Creates a boolean that we will eventually return, and it starts as true.
                      boolean ret = true;
                      //Checks the front of the string for unhappy g's
                      if (str.charAt(0) == 'g' && str.charAt(1) != 'g')
                      {
                        return false;
                      }
                      //Checks the end of the string for unhappy g's
                      if (str.charAt(str.length()-1) == 'g' && str.charAt(str.length()-2) != 'g')
                      {
                        return false;
                      }
                      //Create a while loop that finds out if there are any 'g's that are unhappy in the middle
                      int incre = 1;
                      //While there is an instance of 'g':
                      while (str.indexOf('g', incre) != -1)
                      {
                        //If there is no g to the left or the right of that g, we return false.
                        if (str.charAt(str.indexOf('g', incre) - 1) != 'g' && str.charAt(str.indexOf('g', incre) + 1) != 'g')
                        {
                          return false;
                        }
                        //If there is, then we increment our search place by one character, the one after the 'g'.
                        else
                        {
                          incre = str.indexOf('g', incre) + 2;
                        }
                      }
                      return ret;
                    }
                    else if (str.length() == 2)
                    {
                      //If both chars are 'g', we know to return true since there are only 2 chars.
                      if (str.charAt(0) == 'g' && str.charAt(1) == 'g')
                      {
                        return true;
                      }
                      //If we find a 'g', alone, we return false;
                      else
                      {
                        return false;
                      }
                    }
                    //If the character is one character and a g, we return false.
                    else
                    {
                      return false;
                    }
                  }
                  //If there is no instance of 'g', we return true.
                  else
                  {
                    return true;
                  }
                }
            

            【讨论】:

            • 我想我可以做“incre = str.indexOf('g', incre) + 2;”,这同样有效,因为我们知道下一个 'g' 连接到前一个,否则char不是'g'。这就是我将其更改为的内容。
            【解决方案7】:
            public boolean gHappy(String str)
            {
            
               Boolean flag=true;
            
               if(str.length()<1){
            
                  return flag;
               }
            
               if(str.length()==1 || (str.charAt(str.length()-1)=='g' &&
                  str.charAt(str.length()-2)!='g')){
            
                  return false;
               }
               for(int i=0;i<str.length();i++){
            
               if( i>=0 && i<str.length()-1 && str.charAt(i)=='g' &&
                  (str.charAt(i+1)=='g' || str.charAt(i-1)=='g'))
               {
                  flag=true;
               }
               else if(i>=0 && i<str.length()-1 && str.charAt(i)=='g'&& (!(str.charAt(i+1)=='g' ||
                  str.charAt(i-1)=='g'))){
            
                  flag=false;
            
               }
            }
            
               return flag;
            }
            

            【讨论】:

              【解决方案8】:

              这是我的解决方案:

              public boolean gHappy(String str) {
                int strLength = str.length();
                if(strLength == 1 && str.charAt(0) == 'g') {
                  return false;
                }
                if(strLength > 1 && str.charAt(strLength-1) == 'g' && str.charAt(strLength-2) != 'g') {
                  return false;
                }
                for(int i=1; i<strLength-1; i++) {
                  if(strLength > 2 && str.charAt(i) == 'g' && (str.charAt(i+1) != 'g' && str.charAt(i-1) != 'g')) {
                    return false;
                  }
                }
                return true;
              }
              

              【讨论】:

                【解决方案9】:

                以下是我的解决方案:我使用了 int count 方法,它工作正常。该方法在循环中使用当前的“g”,寻找除它之外的其他“g”。

                public boolean gHappy(String str) {
                    int g = 0;
                    int happy = 0;
                
                    for (int i = 0; i < str.length(); i++) {
                      if (str.substring(i, i+1).equals("g")) { // finds the current "g"
                        g++; // adds all "g" in the str
                        if (i < str.length()-1 && str.substring(i+1, i+2).equals("g")) {
                          happy++; // adds happy, when another g is after the current "g"
                        } else if (i > 0 && str.substring(i-1, i).equals("g")) {
                          happy++; // adds happy, when g is detected before the current "g"
                        }
                      }
                    }
                    return (g==happy); // return true if all g is happy
                }
                

                【讨论】:

                  猜你喜欢
                  • 2017-03-11
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-12-29
                  • 2015-11-21
                  • 2021-03-04
                  相关资源
                  最近更新 更多