디스커스 중에 min이용해서 끝 값이랑, 현재위치 + k 값하는 게 있었는데, 그렇게 하면 내가 짠 코드의 if, else를 한 개로 합칠 수 있을 듯 하다.
내가 짠 코드
class Solution {
public:
string reverseStr(string s, int k) {
int i=0,j;
char tmp;
while(i<s.length()){
if(i+k < s.length()) {
cout<<"if";
for(j=0;j<k/2;j++){
tmp = s[i+j];
s[i+j] = s[i+k-j-1];
s[i+k-j-1] = tmp;
}
}
else {
for(j=0;j<(s.length()-i)/2;j++){
tmp = s[i+j];
s[i+j] = s[s.length()-j-1];
s[s.length()-j-1] = tmp;
}
}
i=i+2*k;
}
return s;
}
};
Success
Runtime: 8 ms, faster than 33.95% of C++ online submissions for Reverse String II.
Memory Usage: 7.1 MB, less than 94.68% of C++ online submissions for Reverse String II.
Discuss 코드 1
class Solution {
public:
/**
* 0 k 2k 3k
* |-----------|-----------|-----------|---
* +--reverse--+ +--reverse--+
**/
string reverseStr(string s, int k) {
for (int left = 0; left < s.size(); left += 2 * k) {
for (int i = left, j = min(left + k - 1, (int)s.size() - 1); i < j; i++, j--) {
swap(s[i], s[j]);
}
}
return s;
}
};
Success
Runtime: 4 ms, faster than 94.99% of C++ online submissions for Reverse String II.
Memory Usage: 7.3 MB, less than 87.63% of C++ online submissions for Reverse String II.
leetcode.com/problems/reverse-string-ii/
Reverse String II - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
'Problem Solving > 리트코드' 카테고리의 다른 글
[LeetCode] Arithmetic SlicesSolution (0) | 2021.02.19 |
---|---|
[LeetCode] Linked List Cycle (0) | 2021.02.08 |
[LeetCode] Number of 1 Bits (0) | 2021.02.08 |
[LeetCode] Squares of a Sorted Array (0) | 2021.01.29 |
[LeetCode] 344. Reverse String (0) | 2021.01.27 |