package com.sec.android.app.utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.util.Log; import com.sec.android.app.xmlparse.SSLSocketFactoryEx; public class HttpDownloader { public static final String TAG = "Theme::HttpDownloader"; private URL url = null; /** * @param urlStr * @return */ public String download(String urlStr) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url .openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConn .getInputStream())); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); } /** */ public int downFile(String urlStr, String path, String fileName) { InputStream inputStream = null; try { FileUtils fileUtils = new FileUtils(); if (fileUtils.isFileExist(path + fileName)) { return 1; } else { inputStream = getInputStreamFromUrl(urlStr); File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream); if (resultFile == null) { return -1; } } } catch (Exception e) { e.printStackTrace(); return -1; } finally { try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } return 0; } /** * * @param urlStr * @return * @throws MalformedURLException * @throws IOException */ public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConn.getInputStream(); return inputStream; } /** * @param url */ public String getStringByUrl(String url) { Log.i(TAG, "start connect.."); String outputString = ""; HttpClient httpclient = SSLSocketFactoryEx.getNewHttpClient(); // HttpGet HttpGet httpget = new HttpGet(url); HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 5 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); // ResponseHandler //ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { HttpResponse response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() == 200) { outputString = EntityUtils.toString(response.getEntity()); outputString = new String(outputString.getBytes("ISO-8859-1"), "utf-8"); } //outputString = httpclient.execute(httpget, responseHandler); //outputString = new String(outputString.getBytes("ISO-8859-1"), "utf-8"); Log.i(TAG, "connect success"); } catch (Exception e) { Log.d(TAG, "connect fail, exception = "+e.toString()); e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); return outputString; } public static String getContent(String url) throws Exception{ StringBuilder sb = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 3000); HttpConnectionParams.setSoTimeout(httpParams, 5000); HttpResponse response = client.execute(new HttpGet(url)); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192); String line = null; while ((line = reader.readLine())!= null){ sb.append(line + "/n"); } reader.close(); } return sb.toString(); } public static boolean isNetworkConnected(Context context) { boolean isConnected = false; if (context != null) { ConnectivityManager con=(ConnectivityManager)context.getSystemService(Activity.CONNECTIVITY_SERVICE); boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); if(wifi|internet){ isConnected = true; } } Log.d(TAG, "isNetworkConnected = "+isConnected); return true; } }
下面几个算法,只是暂时为了方便自己查看,不喜勿喷~
package com.string; public class BM { private long time1, time2; private long count; // char c[] = "heinfdnf".toCharArray(); int a = 20; double b=Math.sin(90); private int dist(char c, char T[], int j) { for (int i = j; i >= 1; i--) { if (T[i - 1] == c) return j - i; } return j; } public void bm(String pattern, String test) { char[] p = pattern.toCharArray(); char[] t = test.toCharArray(); int plen = p.length, tlen = t.length; int sum = 0; if (plen < tlen) { System.out.println("模式串大于主串,匹配失败"); } else { int i = tlen, k, j; time1 = System.nanoTime(); while (i <= plen) { k = i; j = tlen; while (j > 0 && p[i - 1] == t[j - 1]) { i--; j--; } if (0 == j) { sum = sum + tlen; System.out.println("在主串中第" + (i + 1) + "位匹配成功."); break; } else { sum = sum + k - (i - 1); i = k + dist(p[i - 1], t, j); if (i > plen) { System.out.println("匹配失败 ."); break; } } } time2 = System.nanoTime(); } System.out.println("BM算法共匹配了 " + sum + " 次 ."); count = time2 - time1; System.out.println("整个BM算法共用时" + count + "ns.\n"); } // private int indexOf(int[] a,int b,int low,int high){ // int index=-1; // if(low>high){ // return index; // } // int mid =(low+high)/2; // if(a[mid]==b){ // return mid+1; // }else{ // int i=indexOf(a,b,low,mid-1); // if(i==-1){ // index=indexOf(a,b,mid+1,high); // }else{ // index=i; // } // } // return index; // } private void divide_PN(int[] a) { int n = a.length; int i = 0; int j = n - 1; int temp; while (i < j) { while (i < j && a[i] < 0) { i++; } while (i < j && a[j] > 0) { j--; } temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } } public static void main(String[] args) throws Exception { // int M=100; // int N=10; // StringBuilder p = new StringBuilder(); // StringBuilder t = new StringBuilder(); // for(int i=0;i<M;i++){ // p.append((int)(Math.random()*10)); // } // char[] pattern = p.toString().toCharArray(); // for(int i=0;i<N;i++){ // t.append(pattern[i+M/2]); // } // char[] dest = t.toString().toCharArray(); String pattern = "osuqmnsowfiunvksjabcdefmnopghijklmnopqryasmfk"; String test = "mnopq"; BM bm = new BM(); bm.bm(pattern, test); // int in = bm.boyerMoore(pattern, dest); // System.out.println(in); int[] a = { 3, 2, -1, 4, -2, -4, 6, -7, -8, 5 }; for (int aa : a) { System.out.print(aa + " "); } System.out.println(); bm.divide_PN(a); for (int aa : a) { System.out.print(aa + " "); } System.out.println(); // int index=bm.indexOf(a, 4, 0, a.length); // System.out.println(index); } }
===========================================================================================================
package com.string; public class HeapSort { /** * 堆排序 * @param a */ protected static void heapSort(int[] a) { int n = a.length; for (int i = n / 2 - 1; i >= 0; i--) { build(a,n,i); } for(int i=0;i<n;i++){ //将第一个根节点和最后n-1-i个叶子结点交换 int temp = a[0]; a[0] = a[n-1-i]; a[n-1-i] = temp; //调整堆 build(a,n-1-i,0); } } /** * 建一个大根堆 * @param a * @param n * @param index */ static void build(int[] a, int n, int index) { int i = index; int j = 2 * i + 1; while (j < n) { if(j+1<n && a[j]<a[j+1]){//如果根节点既有左孩子又有右孩子,且左孩子比右结点大,则左孩子满足要求 j++; } if(a[i]>=a[j]){//如果父节点大于或等于右结点,则满足要求;此子大根堆完成(等于号会影响该算法的稳定性) break; }else{ int temp = a[i]; a[i] = a[j]; a[j] = temp; i=j; j = 2* i +1; } } return; } /*******************************************************************************************/ public static void main(String[] args) { int M = 20000; // int[] a = {1,2,7,9,2,3,4,5,10}; int[] a = new int[M]; for (int j = 0; j < M / 2; j++) { a[j] = j + 3; } for (int i = M / 2 ; i < M; i++) { a[i] = i - M / 2+2; } long ss = System.currentTimeMillis(); heapSort(a); long sa = System.currentTimeMillis(); System.out.println(sa-ss); // for (int i : a) { // System.out.print(i + " "); // } // System.out.println(); } }
==========================================================================================
package com.string; public class LinkedList { Node head; Node rear; LinkedList() { head = new Node(); head.next = null; rear = head; } /** * 双向链表 (尾插法) * * @param data */ void double_insert(int data) { Node node = new Node(); node.data = data; node.next = null; if(head.next==null){ head.next=node; } rear.next = node; node.pre = rear; rear = node; } /** * 双向链表 (头插法) * * @param data */ void doubl_insert(int data) { Node node = new Node(); node.data = data; node.next = head.next; node.next.pre = node; head.next = node; node.pre = head; } /** * 单向链表 尾插法,需要一个尾指针rear * * @param data */ void singly_insert(int data) { Node node = new Node(); node.data = data; node.next = null; if (head.next == null) {//当链表为空时。。 head.next=node; } rear.next = node; rear = node; } /** * 单向链表 头插法,只需要头指针 * * @param data */ void single_insert(int data) { Node node = new Node(); node.data = data; node.next = head.next; head.next = node; } /** * 将HA,HB两个带头结点的单链表归并为HC,空间复杂度为O(1) * * @param ha * HA头结点 * @param hb * HB头结点 * @param hc * HC头结点 */ void list_merge(Node ha, Node hb, Node hc) { Node a, b, rc; a = ha.next; b = hb.next; hc = ha; hc.next = null; rc = hc;// rc为HC的尾结点 while (a != null && b != null) { if (a.data <= b.data) { rc.next = a; a = a.next; rc = rc.next; } else { rc.next = b; b = b.next; rc = rc.next; } if(hc.next==null){//采用尾插法时,需要考虑空链表的情况 hc.next=rc; } } rc.next = null; if (a != null) rc.next = a; if (b != null) rc.next = b; } /** * 已知单链表L(头结点为head),是一个递增有序表,删除表中data值大于或等于min且小于或等于max之间的结点, 同时释放被删结点的空间 * * @param head * @param min * @param max */ void delNode_seq(Node head, int min, int max) { Node h = head.next; Node start = h; Node end; while (h != null && h.data < min) { start = h; h = h.next; } end = start; while (end != null && end.data <= max) { end = end.next; } h.next = end; while (start != end) {// 删除[start,end)之间的结点 Node temp = start.next; start = null; start = temp; } } void delNode_noseq(Node head, int min, int max) {// 非有序表,介绍如上题 Node h = head.next; Node pre = head; while (h != null) { if (between(h, min, max)) { Node temp = h.next; pre.next = h.next; h = null; h = temp; } else { pre = h; h = h.next; } } } void delRepeatNode(Node head) { Node h = head.next; Node pre; Node r; while (h != null) { pre = h; r = pre.next; while (r != null) { if (r.data == h.data) { Node temp = r.next; pre.next = temp; r = null; r = temp; } else { pre = r; r = r.next; } } h = h.next; } } boolean between(Node node, int min, int max) { return (node.data >= min && node.data <= max) ? true : false; } class Node { int data; Node next; Node pre; } }
===========================================================================
package com.string; public class LZT { public static void print(int row) { for (int i = 1; i <= row; i++) { int col = i * (i - 1) + 1; for (int j = 1; j <= col; j++) { if (i == 1) { System.out.print("*"); } else if (j % i == 1) { System.out.print("*"); } else { System.out.print("."); } } System.out.println(); } } /** * 假设X大于或等于Y;反之,将函数中的X、Y位置互换即可 * @param X * @param Y * @return */ public static int count(int X, int Y) { int count = 0; for (int i = 0; i < Y; i++) { for (int j = 0; j < X; j++) { int c = 0; int m = X - j; int n = Y - i; if (i == Y - 1 || j == X - 1) { c = 1; } else if (m < Y && m < n) { c = m; } else { c = n; } count += c; } } return count; } public static void main(String[] args) { print(3); System.out.println(count(3, 3)); } }
============================================================================
package com.string; public class MergeSort { static int count = 0; /** * 将a[0...m-1]和a[m,n-1]归并;时间复杂度为O(m*n),空间复杂度为O(1). 把后半部分插到前半部分 * * @param a * 待排序数组 * @param m */ public static void merge(int[] a, int m) { int i = 0; int j = m; int n = a.length; while (j < n && i < j) { if (a[j] >= a[j - 1]) { break; } else if (a[j] < a[i]) { int temp = a[j]; for (int k = j - 1; k >= i; k--) { a[k + 1] = a[k]; } a[i] = temp; i++; j++; } else { i++; } } } /*******************************************************************************************/ // 将a[0...mid-1]和a[mid,n-1]归并到b中 public static int[] mergeArray(int a[], int mid, int b[]) { int i = 0, k = 0; int j = mid; while (i < mid && j < a.length) { if (a[i] <= a[j]) { b[k++] = a[i++]; } else { b[k++] = a[j++]; } } while (i < mid) { b[k++] = a[i++]; } while (j < a.length) { b[k++] = a[j++]; } return b; } /*******************************************************************************************/ // 将有二个有序数列a[first...mid]和a[mid+1...last]合并。 private static void mergearray(int a[], int first, int mid, int last, int temp[]) { int i = first, j = mid + 1; int m = mid, n = last; int k = 0; while (i <= m && j <= n) { if (a[i] < a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; } while (i <= m) temp[k++] = a[i++]; while (j <= n) temp[k++] = a[j++]; for (i = 0; i < k; i++) a[first + i] = temp[i]; } private static void merge(int a[], int first, int last, int temp[]) { if (first < last) { int mid = (first + last) / 2; merge(a, first, mid, temp); // 左边有序 merge(a, mid + 1, last, temp); // 右边有序 mergearray(a, first, mid, last, temp); // 再将二个有序数列合并 } } public static void mergeSort(int a[]) { int n = a.length; int[] p = new int[n]; merge(a, 0, n - 1, p); } /*******************************************************************************************/ /** * K路归并 * * @param a * @param k */ private static void mut_mergeSort(int[] a, int k) { int n = a.length; int[] temp = new int[n]; mut_merge(a, temp, 0, n, k); } private static void mut_merge(int[] a, int[] temp, int start, int end, int k) { int n = end - start; int len = (n + k / 2) / k; if (n > 0) { for (int i = 1; i <= k; i++) { int st = len * (i - 1); int en = start + len; if (i == k) { end = n; mut_merge(a, temp, st, en, k); } mut_merge(a, temp, st, en, k); } } } /*******************************************************************************************/ /** * 此算法是不稳定的 * * @param a * @param start * @param mid * @param end */ private static void in_place_mergeSort(int[] a, int start, int mid, int end) { if (a[mid] >= a[mid - 1]) { return; } int i = start, j = mid; int step = 0; while (i < mid && j < end) { while (i < mid && j < end && a[i] <= a[j]) { i++; } while (i < mid && j < end && a[i] >= a[j]) {// 此等号破坏了该算法的稳定 j++; step++; } int n = j - 1; exchange(a, i, mid, n); i += step + 1; mid += step; j = mid; step = 0; // c++; if (j >= end || a[mid] >= a[mid - 1]) { break; } } } static int c = 0; private static void exchange(int[] a, int start, int mid, int end) { reverse(a, start, mid - 1); reverse(a, mid, end); reverse(a, start, end); } private static void reverse(int[] a, int start, int end) { int i = start, j = end, temp; for (; i < j; i++, j--) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } /*******************************************************************************************/ public static void main(String[] args) { int M = 80000; int N = 4 * M / 8; int[] a = new int[M]; for (int j = 0; j < N; j++) { a[j] = 9 * j + 1; } for (int i = N; i < M; i++) { a[i] = 2 * (i - N); } int[] b = new int[M]; for (int j = 0; j < M; j++) { b[j] = a[j]; } // for (int aa : b) { // System.out.print(aa + " "); // } // System.out.println(); long s1 = System.currentTimeMillis(); merge(a, N); // mergeSort(a); long e1 = System.currentTimeMillis(); in_place_mergeSort(b, 0, N, M); // HeapSort.heapSort(b); long e2 = System.currentTimeMillis(); System.out.println(e1 - s1 + " " + (e2 - e1) + " "); System.out.println(c); // for (int i = 0; i < N ; i++) { // if (i % 20 == 0) { // System.out.println(); // System.out.print(b[i] + " "); // } else { // System.out.print(b[i]+ " "); // } // } // System.out.println(); } /*******************************************************************************************/ static int cou = 0; static int k = 0; private static void count(int n) { if (n <= 1) { cou += (n + k) / 2; return; } if (n % 2 == 0) { cou += n / 2; count(n / 2); } else { if (k == 0) { int m = (n - k) / 2; cou += m; k = 1; count(m); } else if (k == 1) { int m = (n + k) / 2; cou += m; k = 0; count(m); } } } }
=================================================================
package com.string; public class QuickSort { /*******************************************************************************************/ private static int partition(int[] a, int low, int high) { int l = low; int h = high; int temp = a[l]; while (l < h) { while (l < h && temp < a[h]) { h--; } if (l < h) { a[l] = a[h]; l++; } while (l < h && temp > a[l]) { l++; } if (l < h) { a[h] = a[l]; h--; } } a[l] = temp; return l; } public static void quickSort(int[] a, int low, int high) { if(low<0 || low>=high){ throw new IndexOutOfBoundsException("参数错误or数组下标越界"); } int mid = partition(a, low, high); if (low < mid - 1) { quickSort(a, low, mid - 1); } if (high > mid + 1) { quickSort(a, mid + 1, high); } } /*******************************************************************************************/ public static void main(String[] args) { int[] a = {1,4,6,3,7,2,5}; long s1 = System.currentTimeMillis(); quickSort(a, 0, a.length - 1); long e1 = System.currentTimeMillis(); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } // System.out.print("比较次数:" + c + " 时间:"+(e1-s1)+"ms"); } private QuickSort() { } }
=====================================================================
package com.string; public class Str { private void reverse(Object[] str, int m, int n) { for (; m < n; m++, n--) { Object temp = str[m]; str[m] = str[n]; str[n] = temp; } } /** * 把str左旋转K位 如吧abcde左旋转2位得到cdeab,在线性时间内实现 * * @param str * @param N为数组长度 * @param K为旋转位数 * @return */ public Object[] leftShift(Object[] str, int N, int K) { // 右移K次和右移K%N次是一样的(考虑到可能K大于N的情况) K %= N; reverse(str, 0, K - 1); reverse(str, K, N - 1); reverse(str, 0, N - 1); return str; } /** * @param src * 字典中的单词 * @param des * 要比较的单词,因为要做大量比较,所以转化为字符数组 * @return */ public static boolean compare(String src, String[] des) { int len = src.length(); if (len != des.length) {// 如果长度不相等,肯定不是兄弟单词,则无需比较 return false; } int i = 0;// i等于1是因为首字符已经相同,无需比较 while (i < len) { if (des[i].equals(String.valueOf(src.charAt(i)))) { i++; continue; } return false; } return true; } /** * 判断在目标字符串des中出现的字符是否都可以在目的字符串src中找到。 时间复杂度为O(m+n),空间复杂度为O(1). * * @param src原字符串 * @param des * @return */ private static boolean exists(String src, String des) { int[] hash = new int[52];// 开辟一个辅助数组并清零 int num = 0;// num为辅助数组中元素个数 int index = 0; for (int i = 0; i < des.length(); i++) { int ch = (int) des.charAt(i); if (ch >= 65 && ch <= 90) { index = ch - 65; } else if (ch >= 97 && ch <= 122) { index = ch - 97 + 26; } if (hash[index] == 0) { hash[index] = 1; num++; } } for (int i = 0; i < src.length(); i++) { int ch = (int) src.charAt(i); if (ch >= 65 && ch <= 90) { index = ch - 65; } else if (ch >= 97 && ch <= 122) { index = ch - 97 + 26; } if (hash[index] == 1) { hash[index] = 0; num--; if (num == 0) { break; } } } if (num == 0) return true; return false; } /** * 求任意一个大于1的数的平方根,采用夹逼法(or二分法) * * @param con * @return */ private static float sqrt(float con) { float low = 1; float high = con; float mid = (low + high) / 2; float mark = 0.000001f; float temp = f(mid, con); while (abs(temp) > mark) { if (temp < 0) { low = mid; } else { high = mid; } mid = (low + high) / 2; temp = f(mid, con); } return mid; } private static float abs(float a) { return a <= 0.0f ? 0.0f - a : a; } private static float f(float a, float con) { return a * a - con; } public static void main(String[] args) { String[] s = { "a", "b", "c", "d", "e" }; String string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String str = "bcdefghijklmnopqrstuvwxyzBCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println(compare(string, s) + "-----------"); System.out.println(exists(string,str) + "=========="); new Str().leftShift(s, 5, 2); for (String ss : s) { System.out.print(ss + " "); } System.out.println(); System.out.println(sqrt(4f)); } }