字符串處理
比較版本號
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
0.1 < 1.1 < 1.2 < 13.37
# Ruby
# @param {String} version1
# @param {String} version2
# @return {Integer}
def compare_version(version1, version2)
v1, v2 = version1.split('.'), version2.split('.')
if (temp = v1.size - v2.size) > 0
temp.times do v2 << '0' end
else
(-temp).times do v1 << '0' end
end
v1.size.times do |i|
temp = v1[i].to_i - v2[i].to_i
next if temp == 0
return temp > 0 ? 1 : -1
end
0
end
注意會有1.1 > 1 和1.0 = 1這樣的判例就行了
Compare Version Numbers
最長共同前綴
給出一個由多個字符串組成的數組,返回所有字符串的最長共同前綴。
# Ruby
# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
return '' if strs == []
return strs[0] if strs.length == 1
sorted = strs.sort{ |a, b| a.length <=> b.length }
result = ''
s = sorted[0]
s.length.times do |i|
for j in 1...sorted.length
if sorted[j][0..i] != s[0..i] then
return result
end
end
result = s[0..i]
end
result
end
最後一個單詞的長度
For example,
Given s = “Hello World”,
return 5.
If the last word does not exist, return 0.
# Ruby
# @param {String} s
# @return {Integer}
def length_of_last_word(s)
return 0 if s == ''
strs = s.split
return 0 if strs[-1].nil?
strs[-1].length
end
判斷迴文
For example,
“A man, a plan, a canal: Panama” or “” is a palindrome.
“race a car” is not a palindrome.
/* C solution using pointer */
bool isPalindrome(char* s) {
int len = strlen(s);
if(!len) return true;
char *p1 = s, *p2 = s + len - 1;
while(p1 < p2){
if(!isalnum(*p1)){p1++;continue;}
if(!isalnum(*p2)){p2--;continue;}
if(tolower(*p1++) != tolower(*p2--)) return false;
}
return true;
}