Skip to content

Instantly share code, notes, and snippets.

@ademidun
Last active September 20, 2016 03:53
Show Gist options
  • Save ademidun/27df28cbeaf416bd6b0e4c739bff2030 to your computer and use it in GitHub Desktop.
Save ademidun/27df28cbeaf416bd6b0e4c739bff2030 to your computer and use it in GitHub Desktop.
Week1-2016
public int lengthOfLongestSubstring(String s) {
if(s==null || s.length()==0){
return 0;
}
HashSet<Character> set = new HashSet<Character>();
int max=0;
int i=0;
int start=0;
while(i<s.length()){
char c = s.charAt(i);
if(!set.contains(c)){
set.add(c);
}
else{
max = Math.max(max, set.size());
while(s.charAt(start)!=c && start<i){
set.remove(s.charAt(start));
start++;
}
start++;
}
i++;
}
max = Math.max(max, set.size());
return max;
}
public int[][] generateMatrix(int n) {
if(n<=1){
return new int [n][n];
}
int [] [] mat = new int [n][n];
int[]counter= {0};//so we can pass by reference
Solution solution = new Solution();
solution.moveRight(mat, 0, 0, n, counter);
return mat;
}
public void moveRight(int[][] mat,int r, int c,int limit,int[] counter){
int n= mat[0].length*mat[0].length;
int moves =0;
while(moves<limit){
mat[r][c]=++counter[0];
c++;moves++;
}
if(counter[0]==n){
return;
}
moveDown(mat,r+1,c-1,limit-1,counter);
}
public void moveDown(int[][] mat,int r, int c,int limit, int[] counter){
int n= mat[0].length*mat[0].length;
int moves=0;
while( moves<limit){
mat[r][c]=++counter[0];
r++;moves++;
}
if(counter[0]==n){
return;
}
moveLeft(mat,r-1,c-1,limit,counter);
}
public void moveLeft(int[][] mat,int r, int c,int limit, int[] counter){
int n= mat[0].length*mat[0].length;
int moves=0;
while(moves<limit){
mat[r][c]=++counter[0];
c--;moves++;
}
if(counter[0]==n){
return;
}
moveUp(mat,r-1,c+1,limit-1,counter);
}
public void moveUp(int[][] mat,int r, int c,int limit, int[] counter){
int n= mat[0].length*mat[0].length;
int moves=0;
while(moves<limit){
mat[r][c]=++counter[0];
r--;moves++;
}
if(counter[0]==n){
return;
}
moveRight(mat,r+1,c+1,limit,counter);
}
public boolean isPalindrome(String s) {
s=s.replaceAll("[^A-Za-z0-9 ]", "");
s=s.replaceAll(" ", "");
s=s.toLowerCase();
int length= s.length();
boolean even;
if (length%2==0){
even=true;
}
else{
even=false;
}
//odd algorithm
int mid= (int)Math.floor(length/2);//for 0-indexed array
int even_shift=even?1:0;//shift the middle tracker if even number of characters
for(int i=even?0:1 ;(mid-even_shift-i)>=0; i++){
if(s.charAt(mid-even_shift-i) != s.charAt(mid+i) ){
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment