Today's Problems :
1694. Reformat Phone Number,
2138. Divide a String Into Groups of Size k
두개 모두 주어지는 string input값을 n개씩 끊어 읽어 정형화 하는 문제이다.
문제의 포인트는 아래와 같이 두개이다.
1) 입력값을 n개 씩 끊기
2) 마지막 원소에 대한 예외처리 (기타 예외처리)
입력값을 n개 씩 끊어 읽기 위한 방법으로
1) "%" 를 통해 나머지 연산을 사용하거나.
if(nth%3==0){ // 3개씩 끊어읽을경우
arr[cnt]='-';
nth=0;
cnt++;
}
2) string의 substr을 사용한다.
// i지점부터 k개 복사
ans += temp.substr(i,k);
1694. Reformat Phone Number
문제 요약:
정형화되지 않은 number을 3개의 숫자 마다 '-' 을 넣고 마지막 블록에 대해서 다음과 같은 예외처리를 한다.
예외처리 1) 마지막 원소가 "000-1" 와 같이 한자리로 끝날경우 "00-01"로 바꿀것
("000-11" 과 같이 "11"로 끝나는건 괜찮다)
원래 문제
You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:
- 2 digits: A single block of length 2.
- 3 digits: A single block of length 3.
- 4 digits: Two blocks of length 2 each.
// 구현 방법 1.
class Solution {
public:
string reformatNumber(string number) {
string arr;
arr.resize(150);
int cnt=0;
int nth=0;
for(int i=0; i< number.size(); i++){
int num = int(number[i]);
if(num >= 48 && num <=57){
arr[cnt]=number[i];
cnt++;
nth++;
if(nth%3==0) {
arr[cnt]='-';
nth=0;
cnt++;
}
}
}
int size = cnt-1;
if(arr[size]=='-')
arr.resize(size);
else if(arr[size-1]=='-'){
arr[size-1] = arr[size-2];
arr[size-2] = '-';
arr.resize(cnt);
}
else
arr.resize(cnt);
return arr;
}
};
2138. Divide a String Into Groups of Size k
문제요약 : input s 가 들어오면 k개 만큼 끊어읽고, 마지막 원소의 개수가 k개보다 모자라다면, fill로 채워라.
Input: s = "abcdefghij", k = 3, fill = "x"
Output: ["abc","def","ghi","jxx"]
class Solution {
public:
vector<string> divideString(string s, int k, char fill) {
// 방법 : s에서 k 개 만큼 빼서, vector에 string단위로 붙여 넣으면 된다.
// 반복 횟수 : 끝이 날때까지,
// substr을 사용하면 temp = "aaa" 일때,
// temp2 = temp.substr(0,7)이 가능하다. temp2에는 aaa가 들어간다.
vector<string> box;
int cnt = 0;
while(cnt<s.length()){
string temp = s.substr(cnt,k);
cnt+=k;
box.push_back(temp);
}
int rest = s.length()%k; //잔여개수가 남았을때, 몇번만큼 넣어주어야 하나?
// k-rest 개만큼 더 넣어주면 된다.
if(s.length()%k !=0){
cout<< box.back() << endl;
string* temp = &(box.back());
cout << k-rest << endl;
for(int j=0; j<k-rest;j++){
*temp+=fill;
}
}
return box;
}
};
'leetcode' 카테고리의 다른 글
[LeetCode Curated Algo 170] 253. Meeting Rooms II (0) | 2022.03.24 |
---|---|
[Leetcode Algorithm I, Day2] [leetcode 283, leetcode 167 ][c++] (0) | 2022.02.25 |
[leetcode 35][c++] search Insert Position (0) | 2022.02.23 |
leetcode 56. merge-intervals [c++] [point :이차원벡터 정렬] (0) | 2022.02.04 |
[leetcode] [single number] (0) | 2021.12.24 |