[The sword refers to the offer] Question 57 (two numbers with s) and Question 58 (flip the string)

Question 57: Two numbers whose sum is s

topic:

Given an increasing sorted array and a number s, find two numbers in the array such that their sum is exactly s. If the sum of multiple pairs of numbers is equal to s, output any pair.

Problem solving program:

#include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;

// Algorithm idea:
// 1. Set two pointers, the first pointer points to the first element of the sorted array, and the second pointer points to the position of the last element of the array element
// 2. Find the sum of the elements pointed to by the two pointers. If the sum of the two elements is greater than the input number, the tail pointer moves forward by one; if the sum is less than the input number,
// Then the pointer to the first element is moved one bit backward; if the sum is exactly equal to the input number, then the element pointed to by the two pointers is the number to be searched for

bool FindNumbersWithSum(int data[],int len,int sum,int *num1,int *num2)
{
    bool found = false;
    
    if( data == NULL|| len<1 || num1 == NULL || num2 == NULL )
        return found;
    int ahead = len - 1;
    int behind = 0;
    
    while(behind < ahead)
    {
       long long CurSum = data[ahead]  + data[behind];
        
        if(CurSum == sum)
        {
            *num1 = data[behind];
            *num2 = data[ahead];
            found = true;
            break;
        }
        else if(CurSum > sum)
            ahead--;
        else
            behind++;

    }

    return found;
}

// test case

void test()
{
    int data[100] = {0};
    int i = 0;
    int value;
    printf("Enter a sorted array, ending with -1:\n");
    scanf("%d",&value);

    while(value != -1)
    {
        data[i++] = value;
        scanf("%d",&value);
    }
    int len ​​= i;

    int sum = 0;
    printf("Enter the sum of the numbers to find:\n");
    scanf("%d",&sum);

    int num1;
    int num2;
    bool ret = FindNumbersWithSum(data,len,sum,&num1,&num2);
    if (ret)
        printf("%d = %d + %d\n",sum,num1,num2);
    else
        printf("The sum of two numbers is not found in the sorted array is %d\n",sum);
}

int main(void)
{
    test();
    return 0;
}


Test case:


Problem 2: Sequence of consecutive positive numbers with sum s

Input a positive number s, print out all consecutive positive number sequences (with at least two numbers) whose sum is s. For example, enter 15, since 1+2+3+4+5 = 4+5+6 = 15. So it prints out 3 consecutive sequences 1 ~ 5, 4 ~ 6 and 7 ~ 8.


Problem solving program:

#include<iostream>
#include<stdio.h>
using namespace std;

// Algorithm idea:
// 1. Set up two variables, small = 1, big = 2;
// 2. If the sum of the sequence numbers from small to big is greater than s, you can remove the smaller value in the sequence; if the sum of the sequence is less than s, increase big until it reaches
// small up to (1+s)/2; if the sum of the sequences is equal to s, print out the sequences whose sum is s

// print the sequence of sums s

void PrintContinuosSequence(int small,int big)
{
    for(int i=small;i<=big;i++)
    {
        printf("%d\t",i);
    }
    
    printf("\n");
}


void FindContinuousSequence(int sum)
{
    // determine boundary conditions
   if(sum<3)
        return;
   
    int small = 1;
    int big = 2;
    int end = (1+sum) / 2;
    int CurSum = small + big;
   
    // To ensure that the minimum value in the sequence is less than the value of (1+s)/2
    while(small < end)
    {
        if(CurSum == sum)
            PrintContinuosSequence(small,big);

        // if the sum of the sequence is not equal to s, and the sum of the current sequence is greater than s
        while(CurSum > sum && small < end)
        {
            // remove the smallest value
            Cursum -= small;
            small++;

            if( CurSum == sum )
                PrintContinuosSequence(small,big);
        }
        
        // if the sum of the sequence is less than s
        // The sequence continues to move backwards
        big++;
        Cursum += big;
    }

}


// test case:

void test()
{
    int s;
    printf("Please enter the sum of the sequence:\n");
    scanf("%d",&s);
   
    // get the subsequence of sum s
    FindContinuousSequence(s);
}

int main(void)
{
    test();
    return 0;
}

Test case:



Question 58: Flip the string

Title: Flip word order

   Enter an English sentence, flip the order of the words in the sentence, but not change the order of the characters within the words. For simplicity, punctuation marks are treated like ordinary letters. For example, the input string "I am a student." will output "stundet. a am I ".


Problem solving program:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

// Algorithm idea:
// 1. Reverse the entire string first
// 2. Then reverse the order of each word including punctuation to get the result


void  Reverse(char *pBegin,char* pEnd)
{
   if(pBegin == NULL || pEnd == NULL)
        return;
   
    // String reverse order
    while(pBegin < pEnd)
    {
       char temp = *pBegin;
        *pBegin = *pEnd;
        *pEnd = temp;
    
        pStart++;
        pEnd--;
    }
}

char *ReverseSentence(char *pData)
{
    printf("pData = %s\n",pData);
   if(pData == NULL)
        return NULL;

    // pointer to the first element of the string
    char *pBegin = pData;
    // pointer to the end element of the string
    char *pEnd = pData;
    
    while(*pEnd != '\0')
        pEnd++;

    pEnd--;


    // Flip the entire sentence first, that is, reverse the entire sentence
    Reverse(pBegin,pEnd);

    // Flip each word and punctuation in the sentence

    pBegin = pEnd = pData;

    // Loop through the words in the string and flip
    while(*pBegin != '\0')
    {
        // If it is a space, the pointer to the first element of the word and the tail pointer are moved back one character, skipping the space
       if(*pBegin == ' ')
        {
           pStart++;
            pEnd++;
        }
        // If the tail pointer points to a space or points to '\0', reverse the word order
        else if(*pEnd == ' ' || *pEnd == '\0')
        {
           Reverse(pBegin,--pEnd);

            // Move the tail pointer back one character and continue to traverse
            pEnd++;
            // The head pointer points to the first character of the next word
            pBegin = pEnd;
        }
        else
            pEnd++;

    }
    printf("pData = %s\n",pData);
    return pData;
}

// test case

void test()
{
    char str[] = "I am a student.";
    char *pStr = NULL;
    pStr = ReverseSentence(str);
    if( pStr != NULL )
        printf("The result after reverse order is: %s\n",pStr);
    else
       printf("Program error!\n");

    char *str1 = NULL;
    pStr = ReverseSentence(str1);
    if( pStr != NULL )
        printf("The result after reverse order is: %s\n",pStr);
    else
        printf("Program error!\n");
    
    char str2[] = "beautiful";
    pStr = ReverseSentence(str2);
    if( pStr != NULL )
        printf("The result after reverse order is: %s\n",pStr);
    else
       printf("Program error!\n");     
}

int main(void)
{
    test();
    return 0;
}

Test case:



Topic 2: Rotate a string to the left

The left rotation operation of a string is to transfer several characters in front of the string to the end of the string. Please define a function to implement the function of string left rotation operation. For example, enter the string "abcdefg" and the number 2, and the function will return the result obtained by left-rotating two places, "cdefgab".

Problem solving program:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

// Algorithm idea:
// 1. Flip the first n characters of the string
// 2, then flip the rest of the characters
// 3. Finally, flip the entire string

void Reverse(char *pBegin,char *pEnd)
{
    if(pBegin == NULL || pEnd == NULL)
        return;
    
    while(pBegin < pEnd)
    {
        char temp = *pBegin;        
        *pBegin = *pEnd;
        *pEnd = temp;

        pStart++;
        pEnd--;
    }
}

char *LeftRotateString(char *pStr,int n)
{
   if(pStr != NULL)
    {
        int nLength = strlen(pStr);
        if(nLength >0 && n>0 && n<nLength)
        {
            char *pFirstStart = pStr;
            char *pFirstEnd = pStr + n - 1;
            char *pSecondStart = pStr + n;
            char *pSecondEnd = pStr + nLength - 1;
            
            // Flip the first n characters of the string
            Reverse(pFirstStart,pFirstEnd);
            
            // Flip the back part of the string
            Reverse(pSecondStart,pSecondEnd);

            // flip the entire string
            Reverse(pFirstStart,pSecondEnd);

        }
    }
    
    return pStr;
}

// test case

void test()
{
    char str1[] = "abcdefg";
    int len = strlen(str1);
    char *pstr = NULL;

    pstr = LeftRotateString(str1,0);
    if( pstr == NULL )
        printf("error\n");
    else
        printf("The result of the string %s flipped from the %dth character is: %s\n",str1,0,pstr);

    // Rotate 1 character left
    
    char str2[] = "abcdefg";
    pstr = LeftRotateString(str2,1);
    if( pstr == NULL )
        printf("error\n");
    else
        printf("The result of the string %s flipped from the %dth character is: %s\n",str2,1,pstr);

    // Rotate 2 characters to the left
    char str3[] = "abcdefg";
    pstr = LeftRotateString(str3,2);
    if( pstr == NULL )
        printf("error\n");
    else
        printf("The result of the string %s flipped from the %dth character is: %s\n",str3,2,pstr);

    // left-hand len-1 characters
    char str4[] = "abcdefg";
    pstr = LeftRotateString (str4, len-1);
    if( pstr == NULL )
        printf("error\n");
    else
        printf("The result of the string %s flipped from the %dth character is: %s\n",str4,len-1,pstr);
   
    // left-rotate len characters
    char str5[] = "abcdefg";
    pstr = LeftRotateString (str5, len);
    if( pstr == NULL )
        printf("error\n");
    else
        printf("The result of the string %s flipped from the %dth character is: %s\n",str5,len,pstr);
    
    // left-hand len+1 characters
    char str6[] = "abcdefg";
    pstr = LeftRotateString (str6, len + 1);
    if( pstr == NULL )
        printf("error\n");
    else
        printf("The result of the string %s flipped from the %dth character is: %s\n",str6,len+1,pstr);

    // string is NULL
    pstr = LeftRotateString (NULL, 0);
    if( pstr == NULL )
        printf("error\n");
    else
        printf("The result of the string %s flipped from the %dth character is: %s\n",str1,0,pstr);

}

int main(void)
{
    test();
    return 0;
}

Test case:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324473938&siteId=291194637