Given a string
s
, return the longest palindromic substring ins
.Constraints:
1 <= s.length <= 1000
s
consist of only digits and English letters.
v1.0
class Solution {
public:
void check(string s, int left, int right, int& Maxlen, int& start){
while(left>=0 && right<s.length() && s[left] == s[right]){
left--;
right++;
}
if(Maxlen < right-left+1){
start = left + 1 ;
Maxlen = right-left+1;
}
}
string longestPalindrome(string s) {
int Maxlen=0;
int start=0;
for(int i=0 ; i<s.length() ; i++){
check(s,i,i,Maxlen,start);
check(s,i,i+1,Maxlen,start);
}
return s.substr(start, Maxlen-2);
}
};
參考網路寫法。
以每個字元都做為中心,漸漸往左右發散。
要分兩個狀況:1. odd palindrome 2. even palindrome
小瑕疵:計算出的左邊界與右邊界不會是正確的,會再往左/右多出一個,因此最大長度要再減2。
Runtime: 264 ms, faster than 48.39% of C++ online submissions for Longest Palindromic Substring.
Memory Usage: 231.6 MB, less than 17.80% of C++ online submissions for Longest Palindromic Substring.
The complement of an integer is the integer you get when you flip all the
0
's to1
's and all the1
's to0
's in its binary representation.For example, The integer
5
is"101"
in binary and its complement is"010"
which is the integer2
.Given an integer
num
, return its complement.Constraints:
1 <= num < 2^31
v1.0
class Solution {
public:
int findComplement(int num) {
bitset<32> num2 = num;
num2 = ~num2;
bool flag = false;
for(int i=31 ; i>=0 ; i--){
if(num2[i]==0){
flag = true;
}
else if(num2[i]==1 & flag==false){
num2[i]=0;
}
}
num = num2.to_ulong();
return num;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Number Complement.
Memory Usage: 5.9 MB, less than 37.54% of C++ online submissions for Number Complement.
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers
x
andy
, return the Hamming distance between them.Constraints:
0 <= x, y <= 2^31 - 1
v1.0
class Solution {
public:
int hammingDistance(int x, int y) {
bitset <32> xbit = x;
bitset <32> ybit = y;
xbit = xbit xor ybit;
return xbit.count();
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Hamming Distance.
Memory Usage: 5.9 MB, less than 74.11% of C++ online submissions for Hamming Distance.