반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- 리액트프로젝트
- Bambino
- mysql
- html
- BCIT
- jvm메모리구조
- jsp
- 자바
- job
- DB
- MSA
- Java
- microservices
- servlet
- C
- 웹개발기초
- Programming
- Doit알고리즘코딩테스트
- 안드로이드
- two pointers
- 웹개발
- 데이터베이스
- coding test
- 밤비노
- sql
- MVC
- msa개념
- SpringFramework
- CSS
- 웹개발자
Archives
- Today
- Total
초보 개발자의 기록
[C language] Leetcode — 1768. Merge Strings Alternately 본문
728x90
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * mergeAlternately(char * word1, char * word2){
int len1 = strlen(word1);
int len2 = strlen(word2);
int resultLen = len1 + len2 + 1;
//malloc: memory allocation
//<stdlib.h> required to use malloc
//resultLen is len1+len2+1 byte allocated
char * result = (char*)malloc(resultLen);
int i =0, j=0, k=0;
while(i < len1 && j < len2){
result[k++] = word1[i++];
result[k++] = word2[j++];
}
while(i<len1){
result[k++] = word1[i++];
}
while(j<len2){
result[k++] = word2[j++];
}
result[k] = '\0';
return result;
free(mergeAlternately);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * mergeAlternately(char * word1, char * word2){
size_t len1 = strlen(word1);
size_t len2 = strlen(word2);
//malloc: memory allocation
char * result = (char*) malloc(sizeof(char) * (len1 + len2 + 1));
size_t i = 0, j = 0, k = 0;
for(i = 0, j = 0, k = 0; i < len1 || j < len2; i++, j++){
if(i <len1){
result[k++] = word1[i];
}
if(j<len2){
result[k++] = word2[j];
}
}
result[k] = '\0';
return result;
}
728x90
반응형