要求:给定字符串"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(","); } } } } }
到了这里你看到了什么?
╮(╯▽╰)╭这个可比那个简单多多了
扩展一下吧,我将要求改为:
随机给出一个整数字符串,长度为len,且字符串里面不能有重复的值。请给出如上面所示的输出的做法。
示例:
随机生成数字字符串"7902"
输出 "0279","027","279","02","27","79","0","2","7","9"
只是增加了点难度而已
分析:①不能重复,字符串;②顺序的输出;
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
原文地址:http://wangxin88.blog.51cto.com/3228434/1537598