標籤:字串 通用 字串截取
要求:給定字串"1234"或者"12345",輸出以下序列。
output->
"1234","123","234","12","23","34","1","2","3","4"
"12345","1234","2345","123","234","345","12","23","34","45","1","2","3","4","5"
是否可以給出通用方法呢?
請注意符號問題!!!!!!!!!!
package com.java.interview.algorithm;/** * name: String_Output.java * * date:2014-8-8 20:00:00 * * function: output special string * * copyright: open * * @author wangxin * */public class String_Output {public static void main(String[] args) {String str = "12345";output_string(str);}/** * 輸出指定格式字串 * * @param str */private static void output_string(String str) {int len = str.length();for (int i = 0; i < len; i++) {int count = 0;for (int j = 0; j <= i; j++) {System.out.print("\"" + str.substring(j, len - i + count++)+ "\"");if (i != (len - 1) || j != i) {System.out.print(",");}}}}}
到了這裡你看到了什嗎?
是否類似全排列呢?650) this.width=650;" src="http://img.baidu.com/hi/jx2/j_0039.gif" alt="j_0039.gif" />
╮(╯▽╰)╭這個可比那個簡單多多了
擴充一下吧,我將要求改為:
隨機給出一個整數字串,長度為len,且字串裡面不能有重複的值。請給出如上面所示的輸出的做法。650) this.width=650;" src="http://img.baidu.com/hi/jx2/j_0021.gif" alt="j_0021.gif" />
樣本:
隨機產生數字字串"7902"
輸出 "0279","027","279","02","27","79","0","2","7","9"
650) this.width=650;" src="http://img.baidu.com/hi/jx2/j_0063.gif" alt="j_0063.gif" />
只是增加了點難度而已
分析:①不能重複,字串;②順序的輸出;
package com.java.interview.algorithm;import java.util.Arrays;import java.util.HashSet;import java.util.Set;/** * name: String_Output2.java * * date:2014-8-8 20:30:43 * * function: output special string * * copyright: open * * @author wangxin * */public class String_Output2 {public static void main(String[] args) {String random_String = random_String(4);System.out.println("隨機產生的數字型字串為: \"" + random_String +"\"");System.out.println("output->");output_string(random_String);}private static void output_string(String str) {int len = str.length();for (int i = 0; i < len; i++) {int count = 0;for (int j = 0; j <= i; j++) { System.out.print("\"" + str.substring(j, len - i + count++)+ "\"");if (i != (len - 1) || j != i) {System.out.print(",");}}}}private static String random_String(int len) {if (len <= 0 || len >= 10) {System.out.println("輸入錯誤,應該在1-9之間");return "fasle";}int count = 0;Set<Integer> set = new HashSet<Integer>(len);do {set.add((int) (Math.random() * 9));count = set.size();} while (count < len);int temp[] = new int[len];count = 0;for (Integer integer : set) {temp[count++] = integer;}Arrays.sort(temp, 0, len);String result = "";for (int i : temp) {result += i;}return result;}}
輸出樣本:隨機產生的數字型字串為: "1678"output->"1678","167","678","16","67","78","1","6","7","8"
未最佳化,歡迎最佳化後交流!
本文出自 “路漫漫兮” 部落格,請務必保留此出處http://wangxin88.blog.51cto.com/3228434/1537598