SHU-2016-SummerPractice / AlgorithmExerciseIssues

算法训练相关文件及工单。
https://github.com/SHU-2016-SummerPractice/AlgorithmExerciseIssues/issues
2 stars 0 forks source link

2016-09-20 [1, 3] #53

Open zhaokuohaha opened 7 years ago

zhaokuohaha commented 7 years ago

把没刷过的按顺序刷下来

1. Two Sum 3. Longest Substring Without Repeating Characters

zhaokuohaha commented 7 years ago

1

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        for(int i=0; i<nums.Length-1; i++){
            for(int j=i+1; j<nums.Length; j++){
                if(nums[i]+nums[j]==target)
                    return new int[]{i,j};
            }
        }
        return null;
    }
}
zhaokuohaha commented 7 years ago

3 - 我都不知道怎么过的

public class Solution {
    public int LengthOfLongestSubstring(string s) {
        if(s.Length<2) return s.Length;
        Dictionary<char, int> dic = new Dictionary<char, int>();
        int max = 0;
        for(int left=0,right=0; right<s.Length; right++){
            if(dic.ContainsKey(s[right]) && dic[s[right]] >= left){
                left = dic[s[right]]+1;
                dic[s[right]] = right;
            }
            else if(dic.ContainsKey(s[right])){
                dic[s[right]] = right;
            }
            else{
                dic.Add(s[right], right);
            }
            max = Math.Max(max, right-left+1);
        }
        return max;
    }
}
zhaokuohaha commented 7 years ago

5 没过, 没想通

public class Solution {
    int start = 0;// 回文串的开始 
    int end = 0;//回文串的 结束 
    int max = 0;// 最大长度 
    public string LongestPalindrome(string s) {
        if(s==null || s.Length==1) return s;
        int middle = (s.Length+1)/2-1;
        int left = middle;
        int right = s.Length/2==0 ? middle+1 : middle;
        for(;left >= max/2;left--,right++){
            count(s, left, left);
            count(s, left-1, left);
            count(s, right, right);
            count(s, right-1, right);
        }
        return s.Substring(start, max);
    }

    private void count(string s, int left, int right){
        if(left < 0 || s[left] != s[right])
            return;
        while(left-1>=0 && right+1 < s.Length && s[left-1] == s[right+1]){
            left--;
            right++;
        }
        if(right-left+1 > max){
            start = left;
            end = right;
            max = right-left+1;
        }
    }
}