数谷

时间:2019-01-17 22:45:19

标签: java counter

我正在解决一个Hackkerank的问题,我对此问题还有些犹豫。自从表单结束以来,我已经尝试了足够的方法,并且以某种方式找到了该算法,但是不幸的是,对于大多数输入而言,它都无法解决问题。它适用于一些测试用例。链接为:Counting Valleys

问题陈述

在这里,我们必须计算XYZ人员访问的山谷数。

  • 山谷是指一系列从海平面以下的连续步骤,从海平面向下逐步延伸到海平面直至结束。

对于上一步,它 U ,对下一步是 D 。我们将以字符串形式(例如 UUDDUDUDDUU )给出XYZ人员行进的步数以及上下波动的信息。

样本输入

8
UDDDUDUU

示例输出

1

说明

如果我们将_表示为海平面,将上升表示为/,将下降表示为\,则Gary的远足次数可以绘制为:

_/\      _
   \    /
    \/\/

他进入并离开一个山谷。

算法

根据我的理论:

山谷从下降开始:

  • 遍历并检查字符串中的两对
  • 检查获取的字符串是否等于 DD
  • DD 开始再次从pos开始循环,然后找到 UU 下降的位置
  • 增加计数,中断;
  • 返回计数

但是对于大多数测试用例来说,这种算法都失败了

代码

static int countingValleys(int n, String s) {
    int valleyVisits = 0, i=0;
    String str = "", strOne = "";

    /*Here we make pairs of two, in order to get the valley's visits. Since this visit starts from DD and ends at UU. So first we get the two strings and match with DD */
    while(i<n){
      //Gives the two strings from i to i+2
      str = s.substring(i, i+2);
      i = i+2; //not to start from next, but to the even pair

      //Checking if the pair starts from DD
      if(str.equals("DD")){
        int j = i;
        /* Rerunning the loop to get the end of the valley trip that is UU from this point */
        while(j < n){
          // Getting new strings starting after DD
          strOne = s.substring(j, j+2);
          j = j+2;

          //Similar operation, but the getting the end from DD and then breaks
          if(strOne.equals("UU")){
            valleyVisits++;
            break;
          }
        }
      }
    }

    return valleyVisits;
}

通过测试用例1

8
UDDDUDUU

Expected Output : 1

通过了测试用例2

12
DDUUDDUDUUUD

Expected Output : 2

测试用例1失败

10
DUDDDUUDUU

Expected Output : 2

测试用例2失败

100
DUDUUUUUUUUDUDDUUDUUDDDUUDDDDDUUDUUUUDDDUUUUUUUDDUDUDUUUDDDDUUDDDUDDDDUUDDUDDUUUDUUUDUUDUDUDDDDDDDDD

Expected Output : 2

我快到了,但是我不知道为什么我的逻辑在这里失败了。在此先感谢您的帮助。 :)

6 个答案:

答案 0 :(得分:2)

这个问题的关键是了解什么构成了山谷。从我的阅读中,您只能算出一个山谷。该规则规定山谷以“ ...上升到海平面”结尾。

因此,我们会跟踪自己的水位,只有当我们从海平面以下移动到海平面时,我们才算出一个山谷。这是我的快速尝试:

private int countValleys(String s)
{
    int level = 0; // 0 is sea-level
    int valleys = 0;

    for (char c : s.toCharArray())
    {
        if (c == 'U') {
            level++;
            if (level == 0)
            {
                valleys++;
            }
        }
        else {
            level--;
        }
    }
    return valleys;
}

我运行了以下测试用例(根据您的问题),它们都通过了:

@Test
public void testValleyCounting()
{
    Assert.assertEquals(1, countValleys("UDDDUDUU"));
    Assert.assertEquals(2, countValleys("DDUUDDUDUUUD"));
    Assert.assertEquals(2, countValleys("DUDDDUUDUU"));
    Assert.assertEquals(2, countValleys("DUDUUUUUUUUDUDDUUDUUDDDUUDDDDDUUDUUUUDDDUUUUUUUDDUDUDUUUDDDDUUDDDUDDDDUUDDUDDUUUDUUUDUUDUDUDDDDDDDDD"));
}

请尝试使用所有测试用例,并让我知道是否失败。

答案 1 :(得分:1)

这个问题是要搜索徒步旅行者沿着他的路径爬到海平面的次数。试试这个对我有用的解决方案。

public static int countingValleys(int steps, String path) {
    int s = 0;
    int v = 0;
    for (int i = 0; i < path.length(); i++) {
        if (path.charAt(i) == 'D') {
            s--;
        } else if ((path.charAt(i) == 'U') && (s + 1 == 0)) {
            s++;
            v++;
        } else {
            s++;
        }
    }
    return v;
}

答案 2 :(得分:0)

关键是上升时,您必须检查海平面,而忽略下降趋势以进行快速处理。

这是我简单而精确的解决方案-

static int countingValleys(int n, String s) {

        int valleyCounter = 0, altitude = 0;

        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (ch == 'U') {
                altitude++;
                if (altitude == 0) {
                    valleyCounter++;
                }

            } else {

                altitude--;
            }
        }
        return valleyCounter;
    }

如果仍然不清楚,需要更多说明,可以在此处click

答案 3 :(得分:0)

/* Counting Valleys */
    public static int countingValleys(int steps, String path) {
        int current_position = 0, vally = 0;
        if(steps >= 2 && steps <= 1000000) {
            int previous_position = 0;
            for(char ch: path.toCharArray()) {
                previous_position = current_position;
                if(ch == 'U') {
                    current_position++;
                } else if(ch == 'D') {
                    current_position--;
                }
                if(current_position == 0 & previous_position < 0 ) {
                    vally ++;
                }
            }
        }
        return vally;
    }

答案 4 :(得分:0)

C ++优化的解决方案

n

答案 5 :(得分:0)

此代码在一些测试用例中正常运行,但在某些情况下失败了。我有点卡住了,因为失败的测试用例被锁定在HackerRank中。 Python3。我是stackoverflow的新手。

    def countingValleys(steps,path):
     v=0
     level=0
     i=[]
     for k in range(0,steps-1):
        if path[k]=='D':
            level-=1 
        else:
            level+=1 
        if level==0:
            i.append(k+1) 
        else:
            continue
     for j in i:
        if path[j-1]=='D' or path[j]=='D' or path[j+1]=='D': 
            v+=1

     return v        
    s=int(input())
    p=str(input())
    print(countingValleys(s,p))