判断字符串中是否具有唯一字符
任务描述:
给出一个字符串(可能为空字符串)
- 输出检测的字符串及其长度
- 空字符串是唯一的
- 检测顺序为自左向右
- 输出该字符串中的字符是否唯一,若不唯一指出相同的字符及其在字符串中的位置,并显示其十六进制值
使用以下五个测试用例:
- 长度为0的字符串:
- 长度为1的字符串(标点句号):.
- 长度为6的字符串:abcABC
- 长度为7的字符串(中间包含空格):XYZ ZYX
- 长度为36的字符串(字母"O"用0代替):
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
C
代码:
交互模式中带空格的字符串需要用双引号括起
#include<stdbool.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>typedef struct positionList{int position;struct positionList *next;
}positionList;typedef struct letterList{char letter;int repititions;positionList* positions;struct letterList *next;
}letterList;letterList* letterSet;
bool duplicatesFound = false;void checkAndUpdateLetterList(char c,int pos){bool letterOccurs = false;letterList *letterIterator,*newLetter;positionList *positionIterator,*newPosition;if(letterSet==NULL){letterSet = (letterList*)malloc(sizeof(letterList));letterSet->letter = c;letterSet->repititions = 0;letterSet->positions = (positionList*)malloc(sizeof(positionList));letterSet->positions->position = pos;letterSet->positions->next = NULL;letterSet->next = NULL;}else{letterIterator = letterSet;while(letterIterator!=NULL){if(letterIterator->letter==c){letterOccurs = true;duplicatesFound = true;letterIterator->repititions++;positionIterator = letterIterator->positions;while(positionIterator->next!=NULL)positionIterator = positionIterator->next;newPosition = (positionList*)malloc(sizeof(positionList));newPosition->position = pos;newPosition->next = NULL;positionIterator->next = newPosition;}if(letterOccurs==false && letterIterator->next==NULL)break;elseletterIterator = letterIterator->next;}if(letterOccurs==false){newLetter = (letterList*)malloc(sizeof(letterList));newLetter->letter = c;newLetter->repititions = 0;newLetter->positions = (positionList*)malloc(sizeof(positionList));newLetter->positions->position = pos;newLetter->positions->next = NULL;newLetter->next = NULL;letterIterator->next = newLetter;} }
}void printLetterList(){positionList* positionIterator;letterList* letterIterator = letterSet;while(letterIterator!=NULL){if(letterIterator->repititions>0){printf("\n'%c' (0x%x) at positions :",letterIterator->letter,letterIterator->letter);positionIterator = letterIterator->positions;while(positionIterator!=NULL){printf("%3d",positionIterator->position + 1);positionIterator = positionIterator->next;}}letterIterator = letterIterator->next;}printf("\n");
}int main(int argc,char** argv)
{int i,len;if(argc>2){printf("Usage : %s <Test string>\n",argv[0]);return 0;}if(argc==1||strlen(argv[1])==1){printf("\"%s\" - Length %d - Contains only unique characters.\n",argc==1?"":argv[1],argc==1?0:1);return 0;}len = strlen(argv[1]);for(i=0;i<len;i++){checkAndUpdateLetterList(argv[1][i],i);}printf("\"%s\" - Length %d - %s",argv[1],len,duplicatesFound==false?"Contains only unique characters.\n":"Contains the following duplicate characters :");if(duplicatesFound==true)printLetterList();return 0;
}
输出:
ghosh@Azure:~/doodles$ ./a.out
"" - Length 0 - Contains only unique characters.
ghosh@Azure:~/doodles$ ./a.out .
"." - Length 1 - Contains only unique characters.
ghosh@Azure:~/doodles$ ./a.out abcABC
"abcABC" - Length 6 - Contains only unique characters.
ghosh@Azure:~/doodles$ ./a.out "XYZ YZX"
"XYZ YZX" - Length 7 - Contains the following duplicate characters :
'X' (0x58) at positions : 1 7
'Y' (0x59) at positions : 2 5
'Z' (0x5a) at positions : 3 6
ghosh@Azure:~/doodles$ ./a.out 1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" - Length 36 - Contains the following duplicate characters :
'0' (0x30) at positions : 10 25
ghosh@Azure:~/doodles$ ./a.out " "
" " - Length 3 - Contains the following duplicate characters :
' ' (0x20) at positions : 1 2 3
ghosh@Azure:~/doodles$ ./a.out 2
"2" - Length 1 - Contains only unique characters.
ghosh@Azure:~/doodles$ ./a.out 333
"333" - Length 3 - Contains the following duplicate characters :
'3' (0x33) at positions : 1 2 3
ghosh@Azure:~/doodles$ ./a.out .55
".55" - Length 3 - Contains the following duplicate characters :
'5' (0x35) at positions : 2 3
ghosh@Azure:~/doodles$ ./a.out tttTTT
"tttTTT" - Length 6 - Contains the following duplicate characters :
't' (0x74) at positions : 1 2 3
'T' (0x54) at positions : 4 5 6
ghosh@Azure:~/doodles$ ./a.out "4444 444k"
"4444 444k" - Length 9 - Contains the following duplicate characters :
'4' (0x34) at positions : 1 2 3 4 6 7 8
C#
代码:
using System;
using System.Linq;public class Program
{static void Main{string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"};foreach (string s in input) {Console.WriteLine($"\"{s}\" (Length {s.Length}) " +string.Join(", ",s.Select((c, i) => (c, i)).GroupBy(t => t.c).Where(g => g.Count() > 1).Select(g => $"'{g.Key}' (0X{(int)g.Key:X})[{string.Join(", ", g.Select(t => t.i))}]").DefaultIfEmpty("All characters are unique.")));}}
}
输出:
"" (Length 0) All characters are unique.
"." (Length 1) All characters are unique.
"abcABC" (Length 6) All characters are unique.
"XYZ ZYX" (Length 7) 'X'(0X58) [0, 6], 'Y'(0X59) [1, 5], 'Z'(0X5A) [2, 4]
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" (Length 36) '0'(0X30) [9, 24]
C++
代码:
#include <iostream>
#include <string>void string_has_repeated_character(const std::string& str)
{size_t len = str.length();std::cout << "input: \"" << str << "\", length: " << len << '\n';for (size_t i = 0; i < len; ++i){for (size_t j = i + 1; j < len; ++j){if (str[i] == str[j]){std::cout << "String contains a repeated character.\n";std::cout << "Character '" << str[i]<< "' (hex " << std::hex << static_cast<unsigned int>(str[i])<< ") occurs at positions " << std::dec << i + 1<< " and " << j + 1 << ".\n\n";return;}}}std::cout << "String contains no repeated characters.\n\n";
}int main()
{string_has_repeated_character("");string_has_repeated_character(".");string_has_repeated_character("abcABC");string_has_repeated_character("XYZ ZYX");string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");return 0;
}
输出:
input: "", length: 0
String contains no repeated characters.input: ".", length: 1
String contains no repeated characters.input: "abcABC", length: 6
String contains no repeated characters.input: "XYZ ZYX", length: 7
String contains a repeated character.
Character 'X' (hex 58) occurs at positions 1 and 7.input: "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", length: 36
String contains a repeated character.
Character '0' (hex 30) occurs at positions 10 and 25.
Go
代码:
package mainimport "fmt"func analyze(s string) {chars := []rune(s)le := len(chars)fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)if le > 1 {for i := 0; i < le-1; i++ {for j := i + 1; j < le; j++ {if chars[j] == chars[i] {fmt.Println(" Not all characters in the string are unique.")fmt.Printf(" %q (%#[1]x) is duplicated at positions %d and %d.\n\n", chars[i], i+1, j+1)return}}}}fmt.Println(" All characters in the string are unique.\n")
}func main() {strings := []string{"",".","abcABC","XYZ ZYX","1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ","01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",}for _, s := range strings {analyze(s)}
}
输出:
Analyzing "" which has a length of 0:All characters in the string are unique.Analyzing "." which has a length of 1:All characters in the string are unique.Analyzing "abcABC" which has a length of 6:All characters in the string are unique.Analyzing "XYZ ZYX" which has a length of 7:Not all characters in the string are unique.'X' (0x58) is duplicated at positions 1 and 7.Analyzing "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" which has a length of 36:Not all characters in the string are unique.'0' (0x30) is duplicated at positions 10 and 25.Analyzing "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X" which has a length of 39:Not all characters in the string are unique.'0' (0x30) is duplicated at positions 1 and 11.
Java
代码:
import java.util.HashMap;
import java.util.Map;// Title: Determine if a string has all unique characterspublic class StringUniqueCharacters {public static void main(String[] args) {System.out.printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions");System.out.printf("%-40s %2s %10s %8s %s %s%n", "------------------------", "------", "----------", "--------", "---", "---------");for ( String s : new String[] {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"} ) {processString(s);}}private static void processString(String input) {Map<Character,Integer> charMap = new HashMap<>(); char dup = 0;int index = 0;int pos1 = -1;int pos2 = -1;for ( char key : input.toCharArray() ) {index++;if ( charMap.containsKey(key) ) {dup = key;pos1 = charMap.get(key);pos2 = index;break;}charMap.put(key, index);}String unique = dup == 0 ? "yes" : "no";String diff = dup == 0 ? "" : "'" + dup + "'";String hex = dup == 0 ? "" : Integer.toHexString(dup).toUpperCase();String position = dup == 0 ? "" : pos1 + " " + pos2;System.out.printf("%-40s %-6d %-10s %-8s %-3s %-5s%n", input, input.length(), unique, diff, hex, position);}}
输出:
String Length All Unique 1st Diff Hex Positions
------------------------ ------ ---------- -------- --- ---------0 yes
. 1 yes
abcABC 6 yes
XYZ ZYX 7 no 'Z' 5A 3 5
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ 36 no '0' 30 10 25
JavaScript
代码:
(() => {'use strict';// duplicatedCharIndices :: String -> Maybe (Char, [Int])const duplicatedCharIndices = s => {constduplicates = filter(g => 1 < g.length)(groupBy(on(eq)(snd))(sortOn(snd)(zip(enumFrom(0))(chars(s)))));return 0 < duplicates.length ? Just(fanArrow(compose(snd, fst))(map(fst))(sortOn(compose(fst, fst))(duplicates)[0])) : Nothing();};// ------------------------TEST------------------------const main = () =>console.log(fTable('First duplicated character, if any:')(s => `'${s}' (${s.length})`)(maybe('None')(tpl => {const [c, ixs] = Array.from(tpl);return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}`}))(duplicatedCharIndices)(["", ".", "abcABC", "XYZ ZYX","1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]));// -----------------GENERIC FUNCTIONS------------------// Just :: a -> Maybe aconst Just = x => ({type: 'Maybe',Nothing: false,Just: x});// Nothing :: Maybe aconst Nothing = () => ({type: 'Maybe',Nothing: true,});// Tuple (,) :: a -> b -> (a, b)const Tuple = a => b => ({type: 'Tuple','0': a,'1': b,length: 2});// chars :: String -> [Char]const chars = s => s.split('');// compose (<<<) :: (b -> c) -> (a -> b) -> a -> cconst compose = (...fs) =>x => fs.reduceRight((a, f) => f(a), x);// enumFrom :: Enum a => a -> [a]function* enumFrom(x) {let v = x;while (true) {yield v;v = 1 + v;}}// eq (==) :: Eq a => a -> a -> Boolconst eq = a => b => a === b;// fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c))const fanArrow = f =>// Compose a function from a simple value to a tuple of// the separate outputs of two different functions.g => x => Tuple(f(x))(g(x));// filter :: (a -> Bool) -> [a] -> [a]const filter = f => xs => xs.filter(f);// fst :: (a, b) -> aconst fst = tpl => tpl[0];// fTable :: String -> (a -> String) -> (b -> String)// -> (a -> b) -> [a] -> Stringconst fTable = s => xShow => fxShow => f => xs => {// Heading -> x display function ->// fx display function ->// f -> values -> tabular stringconstys = xs.map(xShow),w = Math.max(...ys.map(length));return s + '\n' + zipWith(a => b => a.padStart(w, ' ') + ' -> ' + b)(ys)(xs.map(x => fxShow(f(x)))).join('\n');};// groupBy :: (a -> a -> Bool) -> [a] -> [[a]]const groupBy = fEq =>// Typical usage: groupBy(on(eq)(f), xs)xs => 0 < xs.length ? (() => {consttpl = xs.slice(1).reduce((gw, x) => {constgps = gw[0],wkg = gw[1];return fEq(wkg[0])(x) ? (Tuple(gps)(wkg.concat([x]))) : Tuple(gps.concat([wkg]))([x]);},Tuple([])([xs[0]]));return tpl[0].concat([tpl[1]])})() : [];// length :: [a] -> Intconst length = xs =>// Returns Infinity over objects without finite length.// This enables zip and zipWith to choose the shorter// argument when one is non-finite, like cycle, repeat etc(Array.isArray(xs) || 'string' === typeof xs) ? (xs.length) : Infinity;// map :: (a -> b) -> [a] -> [b]const map = f => xs =>(Array.isArray(xs) ? (xs) : xs.split('')).map(f);// maybe :: b -> (a -> b) -> Maybe a -> bconst maybe = v =>// Default value (v) if m is Nothing, or f(m.Just)f => m => m.Nothing ? v : f(m.Just);// on :: (b -> b -> c) -> (a -> b) -> a -> a -> cconst on = f =>g => a => b => f(g(a))(g(b));// ord :: Char -> Intconst ord = c => c.codePointAt(0);// showHex :: Int -> Stringconst showHex = n =>n.toString(16);// snd :: (a, b) -> bconst snd = tpl => tpl[1];// sortOn :: Ord b => (a -> b) -> [a] -> [a]const sortOn = f =>// Equivalent to sortBy(comparing(f)), but with f(x)// evaluated only once for each x in xs.// ('Schwartzian' decorate-sort-undecorate).xs => xs.map(x => [f(x), x]).sort((a, b) => a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0)).map(x => x[1]);// take :: Int -> [a] -> [a]// take :: Int -> String -> Stringconst take = n => xs =>'GeneratorFunction' !== xs.constructor.constructor.name ? (xs.slice(0, n)) : [].concat.apply([], Array.from({length: n}, () => {const x = xs.next();return x.done ? [] : [x.value];}));// uncurry :: (a -> b -> c) -> ((a, b) -> c)const uncurry = f =>(x, y) => f(x)(y)// zip :: [a] -> [b] -> [(a, b)]const zip = xs => ys => {constlng = Math.min(length(xs), length(ys)),vs = take(lng)(ys);return take(lng)(xs).map((x, i) => Tuple(x)(vs[i]));};// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]const zipWith = f =>xs => ys => {constlng = Math.min(length(xs), length(ys)),vs = take(lng)(ys);return take(lng)(xs).map((x, i) => f(x)(vs[i]));};// MAIN ---return main();
})();
输出:
First duplicated character, if any:'' (0) -> None'.' (1) -> None'abcABC' (6) -> None'XYZ ZYX' (7) -> 'X' (0x58) at 0, 6
'1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' (36) -> '0' (0x30) at 9, 24
Python
代码:
'''Determine if a string has all unique characters'''from itertools import groupby# duplicatedCharIndices :: String -> Maybe (Char, [Int])
def duplicatedCharIndices(s):'''Just the first duplicated character, andthe indices of its occurrence, orNothing if there are no duplications.'''def go(xs):if 1 < len(xs):duplicates = list(filter(lambda kv: 1 < len(kv[1]), [(k, list(v)) for k, v in groupby(sorted(xs, key=swap),key=snd)]))return Just(second(fmap(fst))(sorted(duplicates,key=lambda kv: kv[1][0])[0])) if duplicates else Nothing()else:return Nothing()return go(list(enumerate(s)))# TEST ----------------------------------------------------
# main :: IO ()
def main():'''Test over various strings.'''def showSample(s):return repr(s) + ' (' + str(len(s)) + ')'def showDuplicate(cix):c, ix = cixreturn repr(c) + (' (' + hex(ord(c)) + ') at ' + repr(ix))print(fTable('First duplicated character, if any:')(showSample)(maybe('None')(showDuplicate))(duplicatedCharIndices)(['', '.', 'abcABC', 'XYZ ZYX','1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ']))# FORMATTING ----------------------------------------------# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):'''Heading -> x display function -> fx display function ->f -> xs -> tabular string.'''def go(xShow, fxShow, f, xs):ys = [xShow(x) for x in xs]w = max(map(len, ys))return s + '\n' + '\n'.join(map(lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),xs, ys))return lambda xShow: lambda fxShow: lambda f: lambda xs: go(xShow, fxShow, f, xs)# GENERIC -------------------------------------------------# Just :: a -> Maybe a
def Just(x):'''Constructor for an inhabited Maybe (option type) value.Wrapper containing the result of a computation.'''return {'type': 'Maybe', 'Nothing': False, 'Just': x}# Nothing :: Maybe a
def Nothing():'''Constructor for an empty Maybe (option type) value.Empty wrapper returned where a computation is not possible.'''return {'type': 'Maybe', 'Nothing': True}# fmap :: (a -> b) -> [a] -> [b]
def fmap(f):'''fmap over a list.f lifted to a function over a list.'''return lambda xs: [f(x) for x in xs]# fst :: (a, b) -> a
def fst(tpl):'''First member of a pair.'''return tpl[0]# head :: [a] -> a
def head(xs):'''The first element of a non-empty list.'''return xs[0] if isinstance(xs, list) else next(xs)# maybe :: b -> (a -> b) -> Maybe a -> b
def maybe(v):'''Either the default value v, if m is Nothing,or the application of f to x,where m is Just(x).'''return lambda f: lambda m: v if (None is m or m.get('Nothing')) else f(m.get('Just'))# second :: (a -> b) -> ((c, a) -> (c, b))
def second(f):'''A simple function lifted to a function over a tuple,with f applied only to the second of two values.'''return lambda xy: (xy[0], f(xy[1]))# snd :: (a, b) -> b
def snd(tpl):'''Second member of a pair.'''return tpl[1]# swap :: (a, b) -> (b, a)
def swap(tpl):'''The swapped components of a pair.'''return (tpl[1], tpl[0])# MAIN ---
if __name__ == '__main__':main()
输出:
First duplicated character, if any:'' (0) -> None'.' (1) -> None'abcABC' (6) -> None'XYZ ZYX' (7) -> 'X' (0x58) at [0, 6]
'1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' (36) -> '0' (0x30) at [9, 24]
判断字符串中是否具有唯一字符相关推荐
- 判断字符串中是否包含指定字符(JavaScript)
判断字符串中是否包含指定字符 indexOf() indexOf()方法可返回某个指定的字符串值在字符串中首次出现的位置.如果要检索的字符串值没有出现,则返回 -1. search() search( ...
- java判断字符串中是否包含某个字符
1 使用String类的contains()方法 contains()方法用于判断字符串中是否包含指定的字符或字符串.语法如下: public boolean contains(CharSequenc ...
- java 包含几个字符_java怎么判断字符串中包含多少个字符
java怎么判断字符串中包含多少个字符 发布时间:2020-06-23 23:13:52 来源:亿速云 阅读:180 作者:Leah java怎么判断字符串中包含多少个字符?针对这个问题,今天小编总结 ...
- java 判断 中文字符_java中判断字符串中是否有中文字符
package com.meritit.test; public class TestChart { public static void main(String[] args) throws Exc ...
- leetcode练习--字符串中第一个唯一字符
查找字符串中第一个唯一的字符,返回其index: 这里我用了hash的方法,没遇到一个新的字符就会将其保存至map中,我以为map里面会按照insert的顺序进行排放,结果map保存成功后输出结果如下 ...
- 判断字符串中是否包含指定字符的N种方法对比
方法一 var str ="abc"; if(str.indexOf("bc")!=-1){// !=-1含有 ==-1不含有 } 方法二 var str =& ...
- qt 判断字符串中是否含有中文字符_Qt 中文字符串问题
一. Qt5假定的执行字符集是UTF8,不再允许用户擅自改动.这样一来,Qt4中setCodecXXX的各种副作用不再存在,而且中文问题更为简单. QString s1 = "汉语" ...
- Excel如何判断某单元格或者字符串中是否包含某些字符?
1.判断字符串是否含有某字符,区分大小写 比如判断字符串中是否包含大写字母A,可用公式=IF(ISNUMBER(FIND("A",A2)),"有"," ...
- java 字符串包含某个字符_java中判断字符串中是否包含某个特定字符串的方法有哪些...
判断一个字符串是否包含某个子串的n种方法: 1.startsWith()方法 2.contains()方法 3.indexOf方法 startsWith()方法 这个方法有两个变体,用于检测字符串是否 ...
最新文章
- android 屏幕旋转180度
- Vue实现仿音乐播放器7-实现音乐榜单效果
- 为什么let在php中报错,PHPlet在Windows下的安装
- 94年出生,她们如今都是985高校博士生导师!
- linux单网卡多拨Adsl,ROS单线多拨pppoe
- elxel表格纸张尺寸_一本书的诞生:纸张知识
- c++ 多态 运行时多态和编译时多态_C++学习笔记之多态
- 近24小时以太坊上的DEX交易量超过150亿美元
- 剑指offer面试题[36]-数组中的逆序对
- Golang、python中的一个异或加密算法,用来加密字符串。
- HashMap底层实现原理解析
- 【OpenCV实战】简洁易懂的车牌号识别Python+OpenCV实现“超详解”(含代码)
- BT.601和BT.656
- 计算机人类的三大科学思维,什么是科学思维:科学思维可以分为理论、实验、计算思维...
- 利用计算机发现了DNA,DNA计算机阅读答案
- Openbci升级版使用方法
- 幻方 java,Java奇数阶幻方实现代码
- 最大值最小值计算机一级,Excel2019中突出数据最大值和最小值的方法详解
- Machine Learning with Python Cookbook 学习笔记 第8章
- 以太坊加密猫Crypto Kitty合约解析
热门文章
- 如何使用计算机处理文件,如何设置电脑自动清理文件
- 安装smartPPT,电脑显示系统桌面就卡住……
- 写给 Java 程序员的前端 Promise 教程
- RaspBerry Pi 系统安装——Raspbian(精简版)
- 亚马逊开店创业 稳扎稳打稳赚钱
- Slave SQL thread retried transaction 10 time(s) in vain, giving up. Consider raising the value of t
- 微信提现功能测试点【杭州多测师】【杭州多测师_王sir】
- 华为面试题目:一头牛重800kg,一座桥承重700kg,牛如何过河?最秀回答秒过!...
- 轻松高效搭建可视化数据网站
- 【微信小程序源码】独立版云贝餐饮连锁V2_2.3.9源码线传小程序,新增堂食订单,支付打印新增下单时间显示