public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); assert 1 <= m && m <= 100 : "out of range, m: " + m; int s = scanner.nextInt(); assert 0 <= s && s <= 900 : "out of range, s: " + s; if (s > 9 * m || (s == 0 && m > 1)) { System.out.println("-1 -1"); return; } if (m == 1 && s == 0) { System.out.println("0 0"); return; } StringBuilder sb = new StringBuilder(); int l = 0; for (int i = 0; i < m; i++) { int d = (s >= 9) ? 9 : s; sb.append(d); s -= d; if (d != 0) { l = i; } } String large = sb.toString(); if (sb.charAt(m - 1) == '0') { sb.setCharAt(l, (char) (sb.charAt(l) - 1)); sb.setCharAt(m - 1, '1'); } String small = sb.reverse().toString(); System.out.printf("%s %s", small, large); }
private void generateParens( ArrayList<String> list, int leftRem, int rightRem, StringBuilder sb, int index) { // number of left parentheses remaining cannot be less than 0 // cannot possibly have a valid string having inserted more // right parentheses than left parentheses if (leftRem < 0 || rightRem < leftRem) return; if (leftRem == 0 && rightRem == 0) list.add(sb.toString()); else { // add left parenthesis if any left if (leftRem > 0) { try { sb.setCharAt(index, '('); } catch (Exception e) { sb.insert(index, "("); } generateParens(list, leftRem - 1, rightRem, sb, index + 1); } // add right parenthesis if valid if (rightRem > leftRem) { try { sb.setCharAt(index, ')'); } catch (Exception e) { sb.insert(index, ")"); } generateParens(list, leftRem, rightRem - 1, sb, index + 1); } } }
@TCB private static void stripBannedCodeunits(StringBuilder sb, int start) { int k = start; for (int i = start, n = sb.length(); i < n; ++i) { char ch = sb.charAt(i); if (ch < 0x20) { if (IS_BANNED_ASCII[ch]) { continue; } } else if (0xd800 <= ch) { if (ch <= 0xdfff) { if (i + 1 < n) { char next = sb.charAt(i + 1); if (Character.isSurrogatePair(ch, next)) { sb.setCharAt(k++, ch); sb.setCharAt(k++, next); ++i; } } continue; } else if ((ch & 0xfffe) == 0xfffe) { continue; } } sb.setCharAt(k++, ch); } sb.setLength(k); }
/** Return next string in the sequence "a", "b", ... "z", "aa", "ab", ... */ static String getNextDirName(String old) { StringBuilder sb = new StringBuilder(old); // go through and increment the first non-'z' char // counts back from the last char, so 'aa'->'ab', not 'ba' for (int ii = sb.length() - 1; ii >= 0; ii--) { char curChar = sb.charAt(ii); if (curChar < 'z') { sb.setCharAt(ii, (char) (curChar + 1)); return sb.toString(); } sb.setCharAt(ii, 'a'); } sb.insert(0, 'a'); return sb.toString(); }
/** * Replace given characters in a given string builder. * The number of characters to replace has to match to number of * characters serving as a replacement. * * @param sb string builder containing a string to be modified * @param from characters to replaced * @param to replacement characters * @return original string builder with replaced characters. */ public static StringBuilder replace(StringBuilder sb, CharSequence from, CharSequence to) { assert from.length() == to.length(); for (int i=0; i<sb.length(); i++) for (int j=0; j<from.length(); j++) if (sb.charAt(i)==from.charAt(j)) sb.setCharAt(i, to.charAt(j)); return sb; }
public int ladderLength1(String beginWord, String endWord, Set<String> wordList) { Set<String> startList = new HashSet<String>(); Set<String> endList = new HashSet<String>(); startList.add(beginWord); endList.add(endWord); int result = 1; while (!startList.isEmpty() && !endList.isEmpty()) { if (startList.size() > endList.size()) { Set<String> k = startList; startList = endList; endList = k; } Set<String> newSet = new HashSet<String>(); for (String word : startList) { for (int i = 0; i < word.length(); i++) { for (char a = 'a'; a <= 'z'; a++) { if (a == word.charAt(i)) continue; StringBuilder temp = new StringBuilder(word); temp.setCharAt(i, a); String newString = temp.toString(); if (endList.contains(newString)) return result + 1; if (wordList.contains(newString)) { wordList.remove(newString); newSet.add(newString); } } } } startList = newSet; result++; } return 0; }
/** @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int times = Integer.parseInt(input.next()); for (int x = 0; x < times; x++) { String next = input.next(); int pos = (next.length() - 1) / 2; String res = ""; StringBuilder build = new StringBuilder(next); String middle = ""; if (next.length() % 2 == 0) { boolean carry = false; for (; pos >= 0; pos--) { int left = Character.getNumericValue(build.charAt(pos)); int right = Character.getNumericValue(build.charAt(build.length() - 1 - pos)); if (left < right) { left++; build.setCharAt(pos, Character.forDigit(left, 10)); break; } else { } } } else { } System.out.println(res); } }
public String encrypt(String input, int key) { StringBuilder encrypted = new StringBuilder(input); String shiftedAlphabetUp = alphabetUp.substring(key) + alphabetUp.substring(0, key); String shiftedAlphabetLow = alphabetLow.substring(key) + alphabetLow.substring(0, key); for (int i = 0; i < encrypted.length(); i++) { char currChar = encrypted.charAt(i); if (alphabetUp.indexOf(currChar) != -1) { int idx = alphabetUp.indexOf(currChar); if (idx != -1) { char newChar = shiftedAlphabetUp.charAt(idx); encrypted.setCharAt(i, newChar); } } else if (alphabetLow.indexOf(currChar) != -1) { int idx = alphabetLow.indexOf(currChar); if (idx != -1) { char newChar = shiftedAlphabetLow.charAt(idx); encrypted.setCharAt(i, newChar); } } } return encrypted.toString(); }
/* * This problem contraints the word to be all lower-case character, which most likely means it requires * you to do stupid constant(26) time operations to the strings. Doing a graph construction, which is * more general, got Time Limit Exception because it is O(n^2) rather than O((26*n)^2). */ public static int ladderLength(String beginWord, String endWord, Set<String> wordDict) { Queue<String> queue = new LinkedList<String>(); queue.add(beginWord); wordDict.remove(beginWord); int ans = 1; while (!queue.isEmpty()) { for (int count = queue.size(); count > 0; --count) { String word = queue.poll(); StringBuilder altWord = new StringBuilder(word); for (int i = 0; i < word.length(); ++i) { char w = altWord.charAt(i); for (char c = 'a'; c <= 'z'; ++c) { if (w == c) continue; altWord.setCharAt(i, c); if (altWord.toString().equals(endWord)) return ans + 1; if (wordDict.contains(altWord.toString())) { queue.add(altWord.toString()); wordDict.remove(altWord.toString()); } altWord.setCharAt(i, w); } } } ++ans; } return 0; }
@Override public String prepareMessage(String string) { String[] commands = string.split(";"); StringBuilder message = new StringBuilder("00000"); for (String command : commands) { try { switch (Integer.parseInt(command)) { case 0: message.setCharAt(0, '1'); break; case 1: message.setCharAt(1, '1'); break; case 2: message.setCharAt(2, '1'); break; case 3: message.setCharAt(3, '1'); break; case 4: message.setCharAt(4, '1'); break; default: break; } } catch (NumberFormatException e) { return message.toString(); } } return message.toString(); }
public static String initcap(Comparable<?> param) throws ParseException { if (param == null) { return null; } String inputStr = param.toString(); StringBuilder output = new StringBuilder(inputStr); boolean needUpper = true; final int len = inputStr.length(); for (int i = 0; i < len; i++) { char c = inputStr.charAt(i); if (needUpper && Character.isLetter(c)) { if (Character.isLowerCase(c)) { output.setCharAt(i, Character.toUpperCase(c)); } needUpper = false; } else if (!needUpper) { if (!Character.isLetterOrDigit(c)) { needUpper = true; } else if (Character.isUpperCase(c)) { output.setCharAt(i, Character.toLowerCase(c)); } } } return output.toString(); }
private StringBuilder getNextPerm(StringBuilder s) { int n = s.length(); // find the highest index i such that s[i] < s[i+1] int i = n; for (int t = 0; t < n - 1; t++) { if (s.charAt(t) < s.charAt(t + 1)) i = t; } // no such i, return null; if (i == n) return null; // find highest index j such that s[i] < s[j]. j exists as at least it's i+1 int j = 0; for (int t = i + 1; t < n; t++) { if (s.charAt(i) < s.charAt(t)) j = t; } // swap s[i], s[j] char tmp = s.charAt(i); s.setCharAt(i, s.charAt(j)); s.setCharAt(j, tmp); // now reverse char from i+1 StringBuilder res = new StringBuilder(s.substring(0, i + 1)) .append(new StringBuilder(s.substring(i + 1)).reverse()); return res; }
public static String makePretty(String str) { char lastChar = ' '; StringBuilder sb = new StringBuilder(str); int whitespaceDist = 0; for (int i = 0; i < sb.length(); i++) { char nowChar = sb.charAt(i); if (nowChar != ' ' && nowChar != '.') { whitespaceDist += 1; } else { if (whitespaceDist == 2) { char b = sb.charAt(i - 1); char a = sb.charAt(i - 2); sb.setCharAt(i - 1, Character.toUpperCase(b)); sb.setCharAt(i - 2, Character.toUpperCase(a)); } } if (lastChar == ' ' || lastChar == '/') { sb.setCharAt(i, Character.toUpperCase(nowChar)); } else { sb.setCharAt(i, Character.toLowerCase(nowChar)); } lastChar = nowChar; } return sb.toString(); }
public static void reverse(int i, int j, StringBuilder input) { char temp; for (; i < j; i++, j--) { temp = input.charAt(i); input.setCharAt(i, input.charAt(j)); input.setCharAt(j, temp); } }
public boolean createEntity(Dao dao, Entity<?> en) { StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "("); // 创建字段 for (MappingField mf : en.getMappingFields()) { if (mf.isReadonly()) continue; sb.append('\n').append(mf.getColumnName()); // 自增主键特殊形式关键字 if (mf.isId() && mf.isAutoIncreasement()) { sb.append(" SERIAL"); } else { sb.append(' ').append(evalFieldType(mf)); // 非主键的 @Name,应该加入唯一性约束 if (mf.isName() && en.getPkType() != PkType.NAME) { sb.append(" UNIQUE NOT NULL"); } // 普通字段 else { if (mf.isUnsigned()) sb.append(" UNSIGNED"); if (mf.isNotNull()) sb.append(" NOT NULL"); if (mf.isAutoIncreasement()) throw Lang.noImplement(); if (mf.hasDefaultValue()) sb.append(" DEFAULT '").append(getDefaultValue(mf)).append('\''); } } sb.append(','); } // 创建主键 List<MappingField> pks = en.getPks(); if (!pks.isEmpty()) { sb.append('\n'); sb.append( String.format( "CONSTRAINT %s_pkey PRIMARY KEY (", en.getTableName().replace('.', '_').replace('"', '_'))); for (MappingField pk : pks) { sb.append(pk.getColumnName()).append(','); } sb.setCharAt(sb.length() - 1, ')'); sb.append("\n "); } // 结束表字段设置 sb.setCharAt(sb.length() - 1, ')'); // 执行创建语句 dao.execute(Sqls.create(sb.toString())); // 创建索引 dao.execute(createIndexs(en).toArray(new Sql[0])); // 创建关联表 createRelation(dao, en); // 添加注释(表注释与字段注释) addComment(dao, en); return true; }
/** * Generates a crypt(3) compatible hash using the DES algorithm. * * <p>Using unspecified characters as salt results incompatible hash values. * * @param original plaintext password * @param salt a two character string drawn from [a-zA-Z0-9./] or null for a random one * @return a 13 character string starting with the salt string * @throws IllegalArgumentException if the salt does not match the allowed pattern */ public static String crypt(final byte[] original, String salt) { if (salt == null) { final Random randomGenerator = new Random(); final int numSaltChars = SALT_CHARS.length; salt = "" + SALT_CHARS[randomGenerator.nextInt(numSaltChars)] + SALT_CHARS[randomGenerator.nextInt(numSaltChars)]; } else if (!salt.matches("^[" + B64.B64T + "]{2,}$")) { throw new IllegalArgumentException("Invalid salt value: " + salt); } final StringBuilder buffer = new StringBuilder(" "); final char charZero = salt.charAt(0); final char charOne = salt.charAt(1); buffer.setCharAt(0, charZero); buffer.setCharAt(1, charOne); final int eSwap0 = CON_SALT[charZero]; final int eSwap1 = CON_SALT[charOne] << 4; final byte key[] = new byte[8]; for (int i = 0; i < key.length; i++) { key[i] = 0; } for (int i = 0; i < key.length && i < original.length; i++) { final int iChar = original[i]; key[i] = (byte) (iChar << 1); } final int schedule[] = desSetKey(key); final int out[] = body(schedule, eSwap0, eSwap1); final byte b[] = new byte[9]; intToFourBytes(out[0], b, 0); intToFourBytes(out[1], b, 4); b[8] = 0; int i = 2; int y = 0; int u = 128; for (; i < 13; i++) { int j = 0; int c = 0; for (; j < 6; j++) { c <<= 1; if ((b[y] & u) != 0) { c |= 0x1; } u >>>= 1; if (u == 0) { y++; u = 128; } buffer.setCharAt(i, (char) COV2CHAR[c]); } } return buffer.toString(); }
@Override protected void setProductBits(final StringBuilder productBits, final Product product) { if (product == Product.HIGH_SPEED_TRAIN) { productBits.setCharAt(0, '1'); // Hochgeschwindigkeitszug productBits.setCharAt(1, '1'); // IC/EC productBits.setCharAt(2, '1'); // Fernverkehrszug } else if (product == Product.REGIONAL_TRAIN) { productBits.setCharAt(3, '1'); // Regionalverkehrszug } else if (product == Product.SUBURBAN_TRAIN) { productBits.setCharAt(4, '1'); // S-Bahn } else if (product == Product.SUBWAY) { productBits.setCharAt(7, '1'); // U-Bahn } else if (product == Product.TRAM) { productBits.setCharAt(8, '1'); // Stadtbahn } else if (product == Product.BUS) { productBits.setCharAt(5, '1'); // Bus } else if (product == Product.ON_DEMAND) { productBits.setCharAt(9, '1'); // Anruf-Sammel-Taxi } else if (product == Product.FERRY) { productBits.setCharAt(6, '1'); // Schiff } else if (product == Product.CABLECAR) { } else { throw new IllegalArgumentException("cannot handle: " + product); } }
// b static String upperToLower(String input) { StringBuilder sb = new StringBuilder(input); for (int i = 0; i < input.length(); i++) { char toChange = input.charAt(i); if (toChange >= 'a' && toChange <= 'z') { sb.setCharAt(i, Character.toUpperCase(toChange)); } else if (toChange >= 'A' && toChange <= 'Z') { sb.setCharAt(i, Character.toLowerCase(toChange)); } } return sb.toString(); }
/** * @param introspectedColumn * @param inMethod if true generates an "in" method, else generates a "not in" method * @return a generated method for the in or not in method */ private Method getSetInOrNotInMethod(IntrospectedColumn introspectedColumn, boolean inMethod) { Method method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); FullyQualifiedJavaType type = FullyQualifiedJavaType.getNewListInstance(); if (introspectedColumn.getFullyQualifiedJavaType().isPrimitive()) { type.addTypeArgument( introspectedColumn.getFullyQualifiedJavaType().getPrimitiveTypeWrapper()); } else { type.addTypeArgument(introspectedColumn.getFullyQualifiedJavaType()); } method.addParameter(new Parameter(type, "values")); // $NON-NLS-1$ StringBuilder sb = new StringBuilder(); sb.append(introspectedColumn.getJavaProperty()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); sb.insert(0, "and"); // $NON-NLS-1$ if (inMethod) { sb.append("In"); // $NON-NLS-1$ } else { sb.append("NotIn"); // $NON-NLS-1$ } method.setName(sb.toString()); method.setReturnType(FullyQualifiedJavaType.getCriteriaInstance()); sb.setLength(0); if (introspectedColumn.isJDBCDateColumn()) { sb.append("addCriterionForJDBCDate(\""); // $NON-NLS-1$ } else if (introspectedColumn.isJDBCTimeColumn()) { sb.append("addCriterionForJDBCTime(\""); // $NON-NLS-1$ } else if (stringHasValue(introspectedColumn.getTypeHandler())) { sb.append("add"); // $NON-NLS-1$ sb.append(introspectedColumn.getJavaProperty()); sb.setCharAt(3, Character.toUpperCase(sb.charAt(3))); sb.append("Criterion(\""); // $NON-NLS-1$ } else { sb.append("addCriterion(\""); // $NON-NLS-1$ } sb.append(MyBatis3FormattingUtilities.getAliasedActualColumnName(introspectedColumn)); if (inMethod) { sb.append(" in"); // $NON-NLS-1$ } else { sb.append(" not in"); // $NON-NLS-1$ } sb.append("\", values, \""); // $NON-NLS-1$ sb.append(introspectedColumn.getJavaProperty()); sb.append("\");"); // $NON-NLS-1$ method.addBodyLine(sb.toString()); method.addBodyLine("return (Criteria) this;"); // $NON-NLS-1$ return method; }
public List<HtlB2bIncrease> queryIncreasePrice( List<Long> hotelIdParams, List<Long> priceTypeIdParams, Date inDate, Date outDate) { StringBuilder sql = new StringBuilder( " select p.hotel_id,p.room_type_id,p.child_room_type_id,p.base_price,(p.sale_price - p.base_price) as COMMISSION,p.able_sale_date, "); sql.append(" i.INCREASE_RATE,p.currency "); sql.append(" from hwtemp_htl_price p, b2b_increase i "); sql.append(" where p.hotel_id = i.hotel_id "); sql.append(" and i.flag =1 "); sql.append(" and p.pay_method = 'pre_pay' "); sql.append(" and p.able_sale_date >=trunc(?) "); sql.append(" and p.able_sale_date <trunc(?) "); // 离店日期 应该只有小于不能等于 sql.append(" and p.child_room_type_id in ( "); for (Long priceTypeIdParam : priceTypeIdParams) { sql.append(priceTypeIdParam).append(","); } sql.setCharAt(sql.length() - 1, ')'); sql.append(" and p.hotel_id in ( "); for (Long hotelIdParam : hotelIdParams) { sql.append(hotelIdParam).append(","); } sql.setCharAt(sql.length() - 1, ')'); // 这里封装对象 List<Object[]> objects = super.queryByNativeSQL(sql.toString(), new Object[] {inDate, outDate}, null); List<HtlB2bIncrease> htlB2bIncreases = new ArrayList<HtlB2bIncrease>(); for (Object[] obj : objects) { HtlB2bIncrease htlB2bIncrease = new HtlB2bIncrease(); htlB2bIncrease.setHotelId(((BigDecimal) obj[0]).longValue()); // BigDeimal类型 需要转换 htlB2bIncrease.setRoomTypeId(((BigDecimal) obj[1]).longValue()); htlB2bIncrease.setPriceTypeId(((BigDecimal) obj[2]).longValue()); htlB2bIncrease.setBasePrice(((BigDecimal) obj[3]).doubleValue()); htlB2bIncrease.setCommission(((BigDecimal) obj[4]).doubleValue()); htlB2bIncrease.setAbleSaleDate((Date) (obj[5])); double increaseRate = Double.valueOf(String.valueOf(obj[6])); if (increaseRate > 1) { // 设置加幅的是固定金额 htlB2bIncrease.setIncreasePrice( htlB2bIncrease.getBasePrice() + increaseRate / CurrencyBean.getRateToRMB(String.valueOf(obj[7]))); htlB2bIncrease.setCurrency(String.valueOf(obj[7])); } else { // 设置加幅的是比例 htlB2bIncrease.setIncreasePrice( htlB2bIncrease.getBasePrice() + htlB2bIncrease.getCommission() * increaseRate); htlB2bIncrease.setCurrency(String.valueOf(obj[7])); } htlB2bIncreases.add(htlB2bIncrease); } return htlB2bIncreases; }
private Method getSingleValueMethod( IntrospectedColumn introspectedColumn, String nameFragment, String operator) { Method method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); method.addParameter( new Parameter(introspectedColumn.getFullyQualifiedJavaType(), "value")); // $NON-NLS-1$ StringBuilder sb = new StringBuilder(); sb.append(introspectedColumn.getJavaProperty()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); sb.insert(0, "and"); // $NON-NLS-1$ sb.append(nameFragment); method.setName(sb.toString()); method.setReturnType(FullyQualifiedJavaType.getCriteriaInstance()); sb.setLength(0); if (introspectedColumn.isJDBCDateColumn()) { sb.append("addCriterionForJDBCDate(\""); // $NON-NLS-1$ } else if (introspectedColumn.isJDBCTimeColumn()) { sb.append("addCriterionForJDBCTime(\""); // $NON-NLS-1$ } else if (stringHasValue(introspectedColumn.getTypeHandler())) { sb.append("add"); // $NON-NLS-1$ sb.append(introspectedColumn.getJavaProperty()); sb.setCharAt(3, Character.toUpperCase(sb.charAt(3))); sb.append("Criterion(\""); // $NON-NLS-1$ } else { sb.append("addCriterion(\""); // $NON-NLS-1$ } sb.append(MyBatis3FormattingUtilities.getAliasedActualColumnName(introspectedColumn)); sb.append(' '); sb.append(operator); sb.append("\", "); // $NON-NLS-1$ if (introspectedColumn.getFullyQualifiedJavaType().isPrimitive()) { sb.append("new "); // $NON-NLS-1$ sb.append( introspectedColumn.getFullyQualifiedJavaType().getPrimitiveTypeWrapper().getShortName()); sb.append("(value)"); // $NON-NLS-1$ } else { sb.append("value"); // $NON-NLS-1$ } sb.append(", \""); // $NON-NLS-1$ sb.append(introspectedColumn.getJavaProperty()); sb.append("\");"); // $NON-NLS-1$ method.addBodyLine(sb.toString()); method.addBodyLine("return (Criteria) this;"); // $NON-NLS-1$ return method; }
public void f2(StringBuilder ss) { for (int i = 0; i < ss.length(); i++) { char ch = ss.charAt(i); if (ch >= 'a' && ch <= 'z') { // ss = ss.replace(ch, (char)(ch-32)); ss.setCharAt(i, (char) (ch - 32)); } if (ch >= 'A' && ch <= 'Z') { ss.setCharAt(i, (char) (ch + 32)); } } System.out.println(ss); }
// TODO not tested!! public boolean createEntity(Dao dao, Entity<?> en) { StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "("); // 创建字段 for (MappingField mf : en.getMappingFields()) { sb.append('\n').append(mf.getColumnName()); sb.append(' ').append(evalFieldType(mf)); // 非主键的 @Name,应该加入唯一性约束 if (mf.isName() && en.getPkType() != PkType.NAME) { sb.append(" UNIQUE NOT NULL"); } // 普通字段 else { if (mf.isNotNull() || mf.isPk()) sb.append(" NOT NULL"); if (mf.hasDefaultValue()) sb.append(" DEFAULT '").append(getDefaultValue(mf)).append('\''); if (mf.isAutoIncreasement()) sb.append(" generated by default as identity "); if (mf.isPk() && en.getPks().size() == 1) { sb.append(" primary key "); } } sb.append(','); } // 结束表字段设置 sb.setCharAt(sb.length() - 1, ')'); // 执行创建语句 dao.execute(Sqls.create(sb.toString())); // 创建联合主键 if (en.getPks().size() > 1) { sb = new StringBuilder(); sb.append("ALTER TABLE ").append(en.getTableName()).append(" ADD CONSTRAINT PK_"); sb.append(makePksName(en)); sb.append(" PRIMARY KEY ("); for (MappingField mf : en.getPks()) { sb.append(mf.getColumnName()).append(","); } sb.setCharAt(sb.length() - 1, ')'); dao.execute(Sqls.create(sb.toString())); } // 创建关联表 createRelation(dao, en); // 创建索引 dao.execute(createIndexs(en).toArray(new Sql[0])); // 添加注释(表注释与字段注释) addComment(dao, en); return true; }
/** * This convenience wrapper function filters all real transformations that have to be undertaken * on the first string to transform the later into the second string. Both strings have to be * represented by a path that is yielded by the <code>levenshteinPath</code> method of an existing * <code>ComparedStrings</code> object. * * <p>All resulting transformations are represented by <code>String</code> objects that stand for * one step of the transformation. Any further transformation details described by the original * Levenshtein path are lost. Note that the number of transformations is strictly smaller than the * number of Levenshtein path nodes since <code>ACTION_START</code> and <code>ACTION_REMAIN</code> * nodes do not trigger a real transformation and are therefore filtered out. * * @param levenshteinPath The transformation path that alters one string into another * @param firstWord The first word that is represented by <code>levenshteinPath</code> * @param secondWord The second word that is represented by <code>levenshteinPath</code> * @return An array of strings that describes all transformation steps including in their order * @since jLevenshtein v0.2 */ public static String[] resultTransformation( Map<HashPoint, Integer> levenshteinPath, String firstWord, String secondWord) { StringBuilder sb = new StringBuilder(firstWord); char[] secondWordChars = secondWord.toCharArray(); sb.ensureCapacity(secondWordChars.length); int firstWordIndexShifted = 0; List<String> transformations = new ArrayList<String>(levenshteinPath.size() - 1); transformations.add(firstWord); loop: for (Entry<HashPoint, Integer> entry : new TreeMap<HashPoint, Integer>(levenshteinPath).entrySet()) { switch (entry.getValue().intValue()) { case Levenshtein.ACTION_SUBSTITUTE: sb.setCharAt( entry.getKey().y - 1 + firstWordIndexShifted, secondWordChars[entry.getKey().x - 1]); break; case Levenshtein.ACTION_INSERT: sb.insert( entry.getKey().y + firstWordIndexShifted, secondWordChars[entry.getKey().x - 1]); firstWordIndexShifted++; break; case Levenshtein.ACTION_DELETE: sb.deleteCharAt(entry.getKey().y - 1 + firstWordIndexShifted); firstWordIndexShifted--; break; case Levenshtein.ACTION_SWAP: sb.setCharAt( entry.getKey().y - 1 + firstWordIndexShifted, secondWordChars[entry.getKey().x - 1]); sb.setCharAt( entry.getKey().y - 2 + firstWordIndexShifted, secondWordChars[entry.getKey().x - 2]); break; default: continue loop; } transformations.add(sb.toString()); } return transformations.toArray(new String[0]); }
private static void reverse(StringBuilder sb, int start, int end) { for (int i = start, j = end; --j > i; ++i) { char c = sb.charAt(i), d = sb.charAt(j); sb.setCharAt(i, d); sb.setCharAt(j, c); } }
public static StringBuilder toPascalCase(String name) { StringBuilder buffer = toCamelCase(name); char c = buffer.charAt(0); if (c > 96 && c < 123) buffer.setCharAt(0, (char) (c - 32)); return buffer; }
protected List<Sql> createIndexs(Entity<?> en) { List<Sql> sqls = new ArrayList<Sql>(); StringBuilder sb = new StringBuilder(); List<EntityIndex> indexs = en.getIndexes(); for (EntityIndex index : indexs) { sb.setLength(0); if (index.isUnique()) sb.append("Create UNIQUE Index "); else sb.append("Create Index "); if (index.getName().contains("$")) sb.append(TableName.render(new CharSegment(index.getName()))); else sb.append(index.getName()); sb.append(" ON ").append(en.getTableName()).append("("); for (EntityField field : index.getFields()) { if (field instanceof MappingField) { MappingField mf = (MappingField) field; sb.append(mf.getColumnNameInSql()).append(','); } else { throw Lang.makeThrow( DaoException.class, "%s %s is NOT a mapping field, can't use as index field!!", en.getClass(), field.getName()); } } sb.setCharAt(sb.length() - 1, ')'); sqls.add(Sqls.create(sb.toString())); } return sqls; }
public static String unaccentString(CharSequence charSequence) { if (charSequence == null) { return null; } StringBuilder sb = new StringBuilder(charSequence); int s = sb.length(); for (int i = 0; i < s; i++) { char c = sb.charAt(i); if (c == ' ') { sb.setCharAt(i, '_'); } else if (isAccented(c)) { sb.setCharAt(i, unaccented(c)); } } return sb.toString(); }
private static CharSequence ellipsizeFromCache(CharSequence str, int width, TextPaint paint) { // the TextUtils.ellipsize method is really expensive, so we can exploit // the fact that we're using monospace-style text // to just cache the correct number of characters given the width Integer maxLength = PreferenceHelper.ellipsisLengthsCache.get(width); if (maxLength != null) { // cached if (str.length() < maxLength) { return str; } // truncate and add ellipsis StringBuilder stringBuilder = new StringBuilder(str); if (stringBuilder.length() > maxLength) { stringBuilder.delete(maxLength, stringBuilder.length()); } if (stringBuilder.length() > 0) { stringBuilder.setCharAt(stringBuilder.length() - 1, (char) 8230); // add // ellipsis // character } return stringBuilder; } CharSequence result = TextUtils.ellipsize(str, paint, width, TruncateAt.END); if (result.length() < str.length()) { // was ellipsized PreferenceHelper.ellipsisLengthsCache.put(width, result.length()); } return result; }
public String bestmod(String s, int k) { String ret = s; StringBuilder sub = new StringBuilder(s); for (int i = 1, size = s.length(); i < size; ++i) { sub = new StringBuilder( sub.toString().substring(size - 1) + sub.toString().substring(0, size - 1)); StringBuilder sub2 = new StringBuilder(sub); int count = k; for (int j = 1; j <= sub2.length() && count > 0; ++j) { if (sub2.charAt(j - 1) != 'a') { sub2.setCharAt(j - 1, 'a'); --count; } } if (sub2.toString().compareTo(ret) < 0) { ret = sub2.toString(); } } return ret; }