C++: OJ Exercises (Daily Exercise Series)

Programming questions:

Question 1: Adding strings

415. String addition - LeetCode

Idea one:

Step one:Requires to obtain the two tail node subscripts of the string; a>

Second step:Create a variable forrecording the carry number and the obtained string;

Step 3:As long as there is a carry or there are still numbers that have not been added, the cycle will continue: a>;Use ternary arithmetic: signed + sign, unsigned +0

Step 4:Finally reverse the obtained string, which is the desired result.

class Solution {
public:
    string addStrings(string num1, string num2) 
    {
        //获取字符串的尾节点
        int it1 = num1.size() - 1;
        int it2 = num2.size() - 1;
        //记录进位数
        int count = 0;
        //获得的字符串
        string s1 = "";
        //有进位或还有数没有加完
        while(it1 >= 0 || it2 >= 0 || count != 0)
        {
            //三目运算:有符号+符号,无符号+0
            int x = it1 >= 0 ? num1[it1] - '0' : 0;
            int y = it2 >= 0 ? num2[it2] - '0' : 0;
            int n = x + y + count;
            int num = n % 10;
            count = n / 10;
            s1.push_back(num + '0');
            --it1;
            --it2;
        }
        //得到的是逆置的字符串
        reverse(s1.begin(),s1.end());
        return s1;
    }
};

Question 2: Verify palindrome string

125. Verify palindrome string - LeetCode

Idea one:

Step one:Traverse the string, change uppercase to lowercase and delete non-alphabetic and numeric characters;

Second step:Judge whether the symmetric comparison characters are equal;

class Solution {
public:
    bool isPalindrome(string s) 
    {
        //遍历字符串将大写改小写并删除非字母和数字的字符
        for(int i = 0; i < s.size();i++)
        {
            s[i] = tolower(s[i]);
            if((s[i] < 'a' || s[i] > 'z') && (s[i] < '0' || s[i] > '9'))
            {
                s.erase(i,1);
                i--;
            }
        }
        //对称比较字符是否相等
        int left = 0;
        int right = s.size() - 1;
        while(left < right)
        {
            if(s[left] != s[right])
            {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
};

Question 3: Reverse a string

541. Reverse String II - LeetCode

Idea one:

Step one:Create nodes that record the starting position and the end position respectively; a>

Step 2:As long as there are characters after , continue to execute the loop: 1. Counting 2k characters, reverse the first k characters among the 2k characters; 2. The characters are less than 2k but greater than or equal to k, then reverse the first k characters; 3. There are few remaining characters. Out of k characters, reverse all remaining characters.

Special note: reverse is an interval that is closed on the left and open on the right! ! !

class Solution {
public:
    string reverseStr(string s, int k) 
    {
        //分别创建记录起始位置和末尾位置的节点
        string::iterator cur = s.begin();
        string::iterator tail = s.end();
        //只要后面还有字符就继续执行
        while(cur != tail)
        {
            //计数2k 个字符,就反转这2k字符中的前k个字符
            if(cur + 2*k <= tail)
            {
                //需要注意reverse是左闭右开的区间
                reverse(cur,cur + k );
                cur += 2*k;
            }
            //字符小于2k但大于或等于k个,则反转前k个字符
            else if(cur + k <= tail)
            {
                reverse(cur,cur + k );
                break;
            }
            //剩余字符少于k个,将剩余字符全部反转
            else
            {
                reverse(cur,tail);
                break;
            }
        }
        return s;
    }
};

Idea two:

        Reverse a substring of length k starting at each index that is a multiple of 2k. If the length of the substring is less than k, reverse the entire substring.

class Solution {
public:
    string reverseStr(string s, int k) {
        int n = s.length();
        for (int i = 0; i < n; i += 2 * k) {
            reverse(s.begin() + i, s.begin() + min(i + k, n));
        }
        return s;
    }
};

Question 4: Reverse the words in the string

557. Reverse words in a string III - LeetCode

Idea one:

Step one:DefinitionThe variables left and right start from the first character, and tail to record the length of the string ;

Second step:If does not exceed the string length, continue looping: 1. Locate the interval of a word, 2. Reverse (we use subscript access here, reverse cannot be used to reverse), 3. Then eliminate the influence of spaces;

void my_reverse(string& s1,int left,int right)
{
    while(left < right)
    {
        swap(s1[left],s1[right]);
        ++left;
        --right;
    }
}
class Solution {
public:
    string reverseWords(string s) 
    {
        int left = 0;
        int right = 0;
        int tail = s.size();
        //没有超过字符串长度就循环
        while(right < tail)
        {
            //定位一个单词的区间
            while(s[right] != ' ' && s[right] != '\0')
            {
                ++right;
            }
            //逆置
            my_reverse(s,left,right-1);
            //排除空格的影响
            while(s[right] == ' ')
                ++right;
            left = right;
        }
        return s;
    }
};

Question 5: Multiplying strings

43. String multiplication - LeetCode

Idea one:

The first step:Creation: 1. Get the final result of s1, 2. count is used to record carry, and enter is used to record Several multiplications and additions were performed;

Second step:In the while loop, 1.n1 is used as the multiplicand, n2 is used as the multiplier, and tmp is used to record the current product,2. Build a while loop to implement multiplication, 3. Invert the result, 4. Sum the current results of each multiplication(Here, based on the addition of the strings of the question, the range of addition is reduced to achieve multiplication and addition);

The third step:Finally:Judgment: If the string is all '0', return "0", otherwise the normal output calculation The resulting string.

class Solution {
public:
string addStrings(string num1, string num2,int enter) 
    {
        //获取字符串的尾节点
        int it1 = num1.size() - 1 -enter;
        int it2 = num2.size() - 1;
        //记录进位数
        int count = 0;
        //获得的字符串
        string s1 = "";
        //有进位或还有数没有加完
		while(enter--)
		{
			s1.push_back(num1[it1+enter+1]);
		}
        while(it1 >= 0 || it2 >= 0 || count != 0)
        {
            //三目运算:有符号+符号,无符号+0
            int x = it1 >= 0 ? num1[it1] - '0' : 0;
            int y = it2 >= 0 ? num2[it2] - '0' : 0;
            int n = x + y + count;
            int num = n % 10;
            count = n / 10;
            s1.push_back(num + '0');
            --it1;
            --it2;
        }
        //得到的是逆置的字符串
        reverse(s1.begin(),s1.end());
        return s1;
    }
 string multiply(string num1, string num2) 
    {
        //得到最后的结果的s1
        string s1;
        //count用于记录进位
        int count = 0;
        //enter用于记录进行了几次乘加
        int enter = 0;
        //n1做为被乘数
        int n1 = num1.size() - 1;
        while(0 <= n1)
        {
            //n2做为乘数
            int n2 = num2.size() - 1;
            //tmp用于记录当前的乘积
			string tmp;
            //实现乘法
            while(0 <= n2 || count != 0)
            {
				int x = n1 >= 0 ? num1[n1] - '0' : 0;
				int y = n2 >= 0 ? num2[n2] - '0' : 0;
                int num = x * y + count;
                count = num / 10;
                tmp.push_back((num % 10) + '0');
                --n2;
            }
            //所得结果逆置
            reverse(tmp.begin(),tmp.end());
            //对每一次的乘积进行当前结果求和
            s1 = addStrings(s1,tmp,enter);
            ++enter;
			--n1;
        }
        //判断:如果字符串全为‘0’,则返回“0”
        int nn = s1.size() ;
        while(nn--)
        {
            if(s1[nn] - '0' != 0)
            {
                return s1;
            }
        }
        return "0";
    }

};

My ability is limited and my explanation and understanding of some places may not be clear enough. You can try to read the code yourself, or point out the errors in the comment area. Thank you!

Thank you guys for the one-click triple connection! Thank you guys for the one-click three-way connection! Thank you guys for the one-click three-way connection!

                                              

Guess you like

Origin blog.csdn.net/weixin_71964780/article/details/134694290