[Leetcode]Q5練習記錄
阿新 • • 發佈:2018-12-10
給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ n = len(s) if n == 0: return s else: maxNum = 1 start = 0 for i in range(n): count = 1 left = i-1 right = i+1 while left>=0 and right < n: if s[left] == s[right]: count += 2 left -= 1 right += 1 else: break if count>=maxNum: maxNum = count start = left+1 for j in range(n): count = 0 r = j l = j-1 while l>=0 and r<n: if s[l] == s[r]: count += 2 l -= 1 r += 1 else: break if count>=maxNum: maxNum = count start = l+1 return s[start:(start+maxNum)]
class Solution { public: string longestPalindrome(string s) { int n=s.length(); if(n == 0){ return s; } else{ int start = 0; int maxNum = 1; for(int i=0;i<n;i++){ int left = i-1; int right = i + 1; int count = 1; while(left>=0 && right<n){ if(s[left]==s[right]){ count += 2; left -= 1; right += 1; } else{ break; } } if(count>maxNum){ maxNum = count; start = left+1; } } for(int i=0;i<n;i++){ int right = i; int left = i-1; int count = 0; while(left>=0 && right<n){ if(s[left]==s[right]){ count += 2; left -= 1; right += 1; } else{ break; } } if(count>maxNum){ maxNum = count; start = left+1; } } return s.substr(start,maxNum); } } };