在hackerrank 上面的一個問題之C語言解法

2020-08-10 12:14:53

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly  steps. For every step he took, he noted if it was an uphill, , or a downhill,  step. Gary's hikes start and end at sea level and each step up or down represents a  unit change in altitude. We define the following terms:

  • mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
  • valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is , he first enters a valley  units deep. Then he climbs out an up onto a mountain  units high. Finally, he returns to sea level and ends his hike.

Function Description

Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

countingValleys has the following parameter(s):

  • n: the number of steps Gary takes
  • s: a string describing his path

Input Format

The first line contains an integer , the number of steps in Gary's hike.
The second line contains a single string , of  characters that describe his path.

Constraints

  •  
  •  

Output Format

Print a single integer that denotes the number of valleys Gary walked through during his hike.

Sample Input

8
UDDDUDUU

Sample Output

1

Explanation

If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as:

_/\      _
   \    /
    \/\/

He enters and leaves one valley.

 

————————————————————————分割線——————————————————

以上問題其實就是尋找波谷的問題,注意的是,一定是從0開始,到0結束。根據每個步的動作,求和可以得到曲線。思路是得到曲線之後,找到零點數量,當這個零點是從小於0而來的時候,就記錄爲一個山谷,否則就是山峯。

整體程式碼如下:

#include <assert.h>

#include <limits.h>

#include <math.h>

#include <stdbool.h>

#include <stddef.h>

#include <stdint.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

char* readline();

 

// Complete the countingValleys function below.

int countingValleys(int n, char* s) {

 

    int sum=0,dir=0;

    int COUNT;

    for(int i=0;i<n;i++)

    {

        if(s[i]=='U')

            sum++;

        if(s[i]=='D')

            sum--;

        if(sum==0)

        {

            if(dir==-1)

            {

                COUNT++;

            }

            dir=0;

        }

        else if(sum<0)

        {

            dir = -1;

        }

        else

        {

            dir = 1;

        }

    }

    return COUNT;

}

 

int main()

{

    FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

 

    char* n_endptr;

    char* n_str = readline();

    int n = strtol(n_str, &n_endptr, 10);

 

    if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }

 

    char* s = readline();

 

    int result = countingValleys(n, s);

 

    fprintf(fptr, "%d\n", result);

 

    fclose(fptr);

 

    return 0;

}

 

char* readline() {

    size_t alloc_length = 1024;

    size_t data_length = 0;

    char* data = malloc(alloc_length);

 

    while (true) {

        char* cursor = data + data_length;

        char* line = fgets(cursor, alloc_length - data_length, stdin);

 

        if (!line) { break; }

 

        data_length += strlen(cursor);

 

        if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }

 

        size_t new_length = alloc_length << 1;

        data = realloc(data, new_length);

 

        if (!data) { break; }

 

        alloc_length = new_length;

    }

 

    if (data[data_length - 1] == '\n') {

        data[data_length - 1] = '\0';

    }

 

    data = realloc(data, data_length);

 

    return data;

}

 

countingValleys函數爲解法,想明白之後,其實變得很簡單,經驗就是凌晨寫程式碼其實效率真的不高。