2021-07-05 Daily-Challenge
Today I have done Number of Different Integers in a String and leetcode's July LeetCoding Challenge with cpp.
Number of Different Integers in a String
Description
You are given a string word that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".
Return the number of different integers after performing the replacement operations on word.
Two integers are considered different if their decimal representations without any leading zeros are different.
Example 1:
Input: word = "a123bc34d8ef34"
Output: 3
Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
Example 2:
Input: word = "leet1234code234"
Output: 2
Example 3:
Input: word = "a1b01c001"
Output: 1
Explanation: The three integers "1", "01", and "001" all represent the same integer because
the leading zeros are ignored when comparing their decimal values.
Constraints:
1 <= word.length <= 1000wordconsists of digits and lowercase English letters.
Solution
class Solution {
string getNumber(const string &s, int &pos) {
string result;
int len = s.length();
while(pos < len && s[pos] == '0') pos += 1;
while(pos < len && isdigit(s[pos])) {
result.push_back(s[pos]);
pos += 1;
}
if(result.length() > 0) return result;
return "0";
}
public:
int numDifferentIntegers(string word) {
int pos = 0;
int len = word.length();
unordered_set<string> st;
while(pos < len) {
while(pos < len && !isdigit(word[pos])) pos += 1;
if(pos < len) st.insert(getNumber(word, pos));
}
return st.size();
}
};
July LeetCoding Challenge 5
Description
Reshape the Matrix
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the row number and column number of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
Example 2:

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 100-1000 <= mat[i][j] <= 10001 <= r, c <= 300
Solution
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
if(r * c != mat.size() * mat.front().size()) return mat;
int cnt = 0;
vector<int> tmp;
vector<vector<int>> answer;
for(auto &row : mat) {
for(auto num : row) {
tmp.push_back(num);
if(++cnt % c == 0) {
answer.push_back(tmp);
tmp.clear();
}
}
}
return answer;
}
};